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?
O(N)时间的话,不考虑空间,可以用hash。试了一下STL中的unordered_map,可以通过。看来without using extra memory不是强制性的。
#include <unordered_map> using namespace std; class Solution { public: int singleNumber(int A[], int n) { unordered_map<int, int> numbers; unordered_map<int, int>::iterator iter; for (int i = 0; i < n; ++i) { if ((iter = numbers.find(A[i])) != numbers.end()) { ++iter->second; } else { numbers[A[i]] = 1; } } for (iter = numbers.begin(); iter != numbers.end(); ++iter) { if (iter->second != 3) { return iter->first; } } return 0; } };
class Solution { public: int singleNumber(int A[], int n) { int count[32] = {0}; int result = 0; for (int i = 0; i < 32; ++i) { for (int j = 0; j < n; ++j) { count[i] += (A[j] >> i) & 1; } result |= (count[i] % 3) << i; } return result; } };
class Solution { public: int singleNumber(int A[], int n) { int one = 0; int two = 0; int mask = 0; for (int i = 0; i < n; ++i) { two |= one & A[i]; one ^= A[i]; mask = ~(one & two); one &= mask; two &= mask; } return one; } };
===================第二次==============
第三种方法,还得写半天啊,虽然知道思路。当做三进制数,如果某位上1出现次数达到三个则丢弃,最终剩下的就是只出现一次的数。
class Solution { public: int singleNumber(int A[], int n) { int one = 0; int two = 0; int three = 0; for (int i = 0; i < n; ++i) { two |= one & A[i]; one ^= A[i]; three = one & two; one &= ~three; two &= ~three; } return one; } };