Given 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?
1、可以用两层for循环来解决问题,可是时间复杂度为O(n^2),不符合题目要求。
2、用位运算符"^"(异或);
已知:
0 ^ x = x;
x ^ x = 0;
所以x1 ^ x1 ^ x2 ^ x2 ^ ......^ x(n-1) ^ x(n-1) ^xn = 0 ^ 0 ^ 0 ^.......^0 ^ xn = xn。
public int singleNumber(int[] nums) {
int result = 0;
for(int i=0; i<nums.length; i++){
result ^= nums[i];
}
return result;
}
时间复杂度为O(n)符合题目要求。