136. 只出现一次的数字(位运算)

六眼飞鱼酱① 提交于 2020-02-04 15:47:36

在这里插入图片描述
方法一:
利用位运算的性质:
利用 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;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!