Given 2*n + 1
numbers, every numbers occurs twice except one, find it.
Example
Given [1,2,2,1,3,4,3]
, return 4
Challenge
One-pass, constant extra space.
题意
给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
解法一:
1 class Solution { 2 public: 3 /* 4 * @param A: An integer array 5 * @return: An integer 6 */ 7 int singleNumber(vector<int> &A) { 8 int num = A[0]; 9 for (int i = 1; i < A.size(); ++i) { 10 num ^= A[i]; 11 } 12 13 return num; 14 } 15 };
利用异或的性质,相同为0