136.只出现一次的数字

使用哈希表:
class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int num:nums){
            Integer count = map.get(num);
            if(count == null){
                count = 1;
            }else{
                ++count;
            }
            map.put(num,count);
        }
        for(int val:map.keySet()){
            if(map.get(val) == 1){
                return val;
            }
        }
        return 0;
    }
}
 
使用异或:
- 任何数和0异或都是原来的数
 - 任何数和自身异或结果是0
 
class Solution {
    public int singleNumber(int[] nums) {
        int single = 0;
        for (int num : nums) {
            single ^= num;
        }
        return single;
    }
}
                

















