Given 2*n + 1
numbers, every numbers occurs twice except one, find it.
Example
Given [1,2,2,1,3,4,3]
, return 4
Idea 1:
Violent solution, just sort first and then see the difference, although you can AC, but doing this the interviewer is going to beat people...
class Solution { public: /** * @param A: An integer array * @return: An integer */ int singleNumber(vector<int> &A) { // write your code here if(A.size() == 1) return A[0]; sort(A.begin(),A.end()); for(int i=0;i<A.size();i = i+2) { if(A[i] != A[i+1]) return A[i]; } } };
Idea 2:
Through XOR, the result of the same number is 0, then the final result must be the number placed in the order.
3 characteristics of bitwise XOR:
(1) 0^0=0,0^1=1 0 XOR any number=any number
(2) 1^0=1,1^1=0 1 XOR any number - Negate any number
(3) XOR self of any number = set self to 0
The characteristic of XOR operation makes this method widely popularized to count the number of 1 digits of a number!
class Solution { public: /** * @param A: An integer array * @return: An integer */ int singleNumber(vector<int> &A) { // write your code here int years = 0; for(int i=0;i<A.size();i++) years ^= A[i]; return ans; } };