问题描述:一个数组中只有个一个数字出现了一次,其他的数字都出现两次,找出那个出现一次的。
提示:你的算法应在线性时间内完成,且不使用额外的存储空间。
思路:使用map可以在线性时间内完成,但是不使用额外的存储空间却无法做到。
原代码
public int singleNumber(int[] nums) {
int length=nums.length;
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<length;i++){
if(map.containsKey(nums[i]))
map.put(nums[i],map.get(nums[i])+1);
else
map.put(nums[i],1);
}
for(int j=0;j<length;j++){
if(map.get(nums[j])==1)
return nums[j];
}
return 0;
}
最佳答案:
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return Integer.MIN_VALUE;
}
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
res ^= nums[i];
}
return res;
}
不得不说最佳答案很好的利用了题设。其它数字都出现两次保证异或操作后将全是0。而0异或只出现一次的数字将为原数字。真是个精妙的答案。