方法一:
哈希
class Solution {
public int[] singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for(int i : nums){
if(map.containsKey(i)) map.put(i,map.get(i)+1);
else map.put(i,1);
}
int cnt = 0;
int[] res = new int[2];
for(int i:map.keySet()){
if(map.get(i)==1) {
res[cnt] = i;
cnt++;
}
}
return res;
}
}
方法二:
位运算
class Solution {
public int[] singleNumber(int[] nums) {
int diff = 0;
for(int num :nums) diff ^=num;
diff &= -diff;
int[] ret = new int[2];
for(int num :nums){
if((num & diff) == 0) ret[0] ^=num;
else ret[1] ^= num;
}
return ret;
}
}