第一次是使用HashMap解决的,但好像时间和空间都比较浪费。
class Solution {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map=new HashMap();
for(int n:nums) {
Integer val = map.get(n);
if(val==null) val=0;
map.put(n, val+1);
}
for(Map.Entry<Integer,Integer> entry:map.entrySet()) {
if(entry.getValue()==1) return entry.getKey();
}
return 0;
}
}
后来看了题解才知道有更好的方法,即异或运算;原理如下:
-
交换律:a ^ b ^ c <=> a ^ c ^ b
-
任何数于0异或为任何数 0 ^ n => n
-
相同的数异或为0: n ^ n => 0
修改之后:
class Solution {
public int singleNumber(int[] nums) {
int val=0;
for(int num:nums) {
val^=num;
}
return val;
}
}
var code = "c999172f-1ca3-456e-8f83-c1ac4a22d302"