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?
Thoughts
这道题感觉出题人没安什么好心...
1.首先想法是用HashSet或者HashMap,但是需要extra memory O(N)。
2.其次就是sort,直接用sorted array replace掉本来的array,表面上看貌似没有extra memory,但是runtime complexity是O(NlogN)。
3. bit-wise XOR。XOR了所有数组里的数字,剩下的就是没有重复过的。runtime O(N)。但是这种解法下,需要一个变量存储每次XOR之后的结果。
讲道理,stack allocation就不算extra memory嘛?
Solutions
public int singleNumber(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++){
result ^= nums[i];
}
return result;
}