Single Number
My SubmissionsGiven an 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?
思路:两个相同的数异或之后的值为零,那么该题将n个数异或,得到的就是那个single one~
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 (A == 0 || n < 1)
return 0;
int key = A[0];
for (int i = 1; i < n; ++i) {
key ^= A[i];
}
return key;
}
};