Lintcode:落单的数 II

描述

给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。

样例

给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4

挑战

一次遍历,常数级的额外空间复杂度

思路: 在落单的数1中,我们直接将所有的数异或,那么重复的数就直接去掉了,最后的结果就是那个落单的数。

那么在我们这道题中有两种思路:

1. 还是根据位运算,按位计算。int型数字占32位,如果这个数字出现3次,则与这个数字对应的每一位上的1也出现三次。使用int型数组记录每一位上1出现的次数,能被3整除则表示出现3次。最后得到的就是要求的数字。

2. 可以使用hashmap,当一个数遍历三次后从hashmap中去掉。

Java代码:

1.

public int singleNumber2(int[] A) {
        // write your code here
        if(A==null || A.length==0){
            return 0;
        }
        int[] bits = new int[32];
        int res = 0;
        for (int i = 0; i < 32; i++) {
            for (int j = 0; j < A.length; j++) {
                bits[i] += A[j]>>i & 1;
            }
            bits[i] = bits[i] % 3;
            res = res | bits[i]<<i;
        }
        return res;
    }

2.

    public int singleNumberII(int[] A) {
        // write your code here
        if(A==null || A.length==0){
            return 0;
        }
        Map<Integer, Integer> hashmap = new HashMap<>();
        for (int i : A) {
            if(hashmap.containsKey(i)){
                if(hashmap.get(i)==2){
                    hashmap.remove(i);
                }else{
                    hashmap.put(i,hashmap.get(i)+1);
                }
            }else{
                hashmap.put(i,1);
            }

        }
        Set<Integer> set = hashmap.keySet();
        Iterator<Integer> it = set.iterator();
        return it.next();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值