看见这题我的第一反应是用哈希来做,不过更简洁的做法是用异或来处理,只要是偶数个都为0(0和任意数异或仍为数本身)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int singleNumber(int A[], int n) { int x = 0; for (int i = 0; i < n; i++) x ^= A[i]; return x; }
这题的思路更加巧妙,需好好琢磨,思路如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int singleNumber2(int A[], int n) { int one, two, three; one = two = three = 0; for (int i = 0; i < n; i++) { three = two & A[i];//已经出现了两次,再出现了一次 two = two | (one &A[i]); one = one | A[i]; //去掉出现三次的 one = one &(~three); two = two &(~three); } return one; }