剑指 Offer 56 - II. 数组中数字出现的次数 II

使用map的方法:

class Solution {
    public int singleNumber(int[] nums) {
        //数组中一个数字出现一次,剩下的数字都出现了三次,要找到那个只出现一次的数字
        //首先想到的是map记录每个数出现多少次。
        if(nums==null || nums.length==0){
            return 0;
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int temp:nums){
           if(map.containsKey(temp)){
               map.put(temp,2);
           }else{
                map.put(temp,1);
           }
        }
        for(int temp:nums){
            if(map.get(temp)==1){
                return temp;
            }
        }
        return 0;
    }
}

使用位运算的方法:

一个长32的数组(因为int  4byte,32位),遍历数组中的每个元素,把他们的每一位储存进数组中。最后得到的数组中元素%3,再或运算与0000000000... 拼接起来得到的就是所求数啦。这个方法比较简单,时间n  空间1(恒定大小的数组)。

class Solution {
    public int singleNumber(int[] nums) {
        int[] counts = new int[32];
        for(int num : nums) {
            for(int j = 0; j < 32; j++) {
                counts[j] += num & 1;
                num >>>= 1;
            }
        }
        int res = 0, m = 3;
        for(int i = 0; i < 32; i++) {
            res <<= 1;
            res |= counts[31 - i] % m;
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值