[LeetCode] Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n < 1 || n %3 != 1)
return -1;
map<int, int> mp;
map<int, int> ::iterator it;
for(int i = 0; i < n; i++) {
it = mp.find(A[i]);
if(it == mp.end())
mp[A[i]] = 1;
else
mp[A[i]] += 1;
}
for(it = mp.begin(); it != mp.end(); it++) {
if(it->second != 3)
return it->first;
}
}
};
这里用到了一种取巧的方法,感觉有违本意。下次再来换下别的方法。