public int singleNumber(int[] nums) {
HashMap<Integer, Boolean> hashMap = new HashMap<>();
// 遍历将出现一次的数字value置为true,出现多次的value置为false
for (int num : nums){
if (hashMap.get(num) == null){
hashMap.put(num, true);
}else {
hashMap.put(num, false);
}
}
int res = -1;
// 找到value为true的数字
for(int key: hashMap.keySet()){
if (hashMap.get(key)){
res = key;
break;
}
}
return res;
}
我用的笨方法 来看看大神是怎么解的
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for(int num : nums){
ones = ones ^ num & ~twos;
twos = twos ^ num & ~ones;
}
return ones;
}