问题描述:
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
思路:
用哈希表实现。把数值设为key,把出现的次数设为value。插入map前先检查,如果有这个元素,则替换原键值对的value为2;若没有这个元素,则插入该键值对且value为1.
难点在于搜索value=1的key。hashmap没有直接由value找key的操作,所以要扫描所有的key,如果这个key的value=1,则返回这个key。
代码如下:
class Solution {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int i =0; i<nums.length; i++){
if (!map.containsKey(nums[i])){
map.put(nums[i], 1);
}
else{
map.replace(nums[i],2);
}
}
for (Integer key : map.keySet()){
if (map.get(key)==1){
return key;
}
}
return -1;
}
}
时间复杂度: O(n)
巧妙方法:
class Solution {
public int singleNumber(int[] nums) {
int a = 0;
for (int i : nums) {
a ^= i;
}
return a;
}
}
a xor b xor a = b
假如有5个元素{4,1,2,1,2}
4=1000
1=0001
2=0010
设a=0000
a xor 4 = 1000
1000 xor 1 = 1000 xor 0001 = 1001
1001 xor 2 = 1001 xor 0010 = 1011
1011 xor 1 = 1011 xor 0001 = 1010
1010 xor 2 = 1010 xor 0010 = 1000 = 4