Given an array of integers, every element appears twice except for one. Find that single one.
这一题第一反应是 直接存个map,<数值,出现次数>作为键值对。
但是这一题要求 不要有extra memory,同时时间复杂度为O(n);
直接想到异或^,两个数相异为1,相同为0。所以把数组整个异或一遍,出来的值就是那个只有一次的数。
代码如下:
public class Solution {
public int singleNumber(int[] nums) {
for(int i = 1; i<nums.length; i++) {
nums[0] ^=nums[i];
}
return nums[0];
}
}