方法一:
利用位运算的性质:
利用 x ^ x = 0 的特点,可以将三个数中重复的两个数去除,只留下另一个数。
例如:2,1,2
2^1 = 3,
3^2 = 1
class Solution {
public int singleNumber(int[] nums) {
int res = nums[0];
for(int i = 1;i<nums.length;i++){
res = res^nums[i];
}
return res;
}
}
方法二:
用哈希表
class Solution {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for(int i :nums){
Integer cnt = map.get(i);
cnt = cnt == null ? 1:++cnt;
map.put(i,cnt);
}
for(int i :map.keySet()){
if(map.get(i) == 1) return i;
}
return -1;
}
}