Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Teach Your Child To Read

Disclosure: My content contains affiliate links.

31,649 questions

41,702 answers

573 users

How to find an element that appears once in a vector of elements that appears three times in C++

2 Answers

0 votes
#include <unordered_map>
#include <iostream>
#include <vector>

int findElementThatAppearsOnceInArray(std::vector<int>& vec) {
    std::unordered_map<int, int> map;
        
    for (auto x: vec) {
        map[x]++;
    }

    for (auto x: map) {
        if (x.second == 1) {
            return x.first;
        }
    }
    
    return -1;
}


int main() {
    std::vector<int> vec {3, 5, 5, 2, 7, 3, 2, 8, 8, 3, 2, 5, 8};
         
    std::cout << findElementThatAppearsOnceInArray((vec));
}



/*
run:

7

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Jul 8 by avibootz
0 votes
#include <iostream>
#include <vector>

int findElementThatAppearsOnceInArray(std::vector<int>& vec) {
    int result = 0;

    for (int i = 0; i < 32; ++i) {
        int sum = 0;
        for (const int num : vec) {
            sum += num >> i & 1;
        }
        sum %= 3;
        result |= sum << i;
    }

    return result;
}

int main() {
    std::vector<int> vec {3, 5, 5, 2, 7, 3, 2, 8, 8, 3, 2, 5, 8};
         
    std::cout << findElementThatAppearsOnceInArray((vec));
}



/*
run:

7

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Jul 8 by avibootz
...