I am trying to implement this problem in C++ using unordered map
:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1Example 2:
Input: [4,1,2,1,2]
Output: 4
My solution:
class Solution {
public:
int singleNumber(vector<int>& nums) {
std::unordered_map<int, int> umap;
for (auto i = nums.begin(); i != nums.end(); i++) {
umap[*i] = umap[*i] + 1;
}
for (auto i = umap.begin(); i != umap.end(); i++) {
if (umap[*i] == 1) {
return *i;
}
}
}
};
But unfortunately, it does not work. I get this error while compiling
Line 16: Char 17: fatal error: no viable overloaded operator[] for type 'std::unordered_map' if (umap[*i] == 1) { ~~~~^~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/unordered_map.h:973:7: note: candidate function not viable: no known conversion from 'std::pair' to 'const std::unordered_map, std::equal_to, std::allocator > >::key_type' (aka 'const int') for 1st argument operator[](const key_type& __k) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/unordered_map.h:977:7: note: candidate function not viable: no known conversion from 'std::pair' to 'std::unordered_map, std::equal_to, std::allocator > >::key_type' (aka 'int') for 1st argument operator[](key_type&& __k) ^ 1 error generated.
I cannot understand the error. Can anyone explain to me?
unordered_map
. This is a question where if you don't know the trick, you may never solve it. – PaulMcKenzie