LeetCode 笔记26 Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

没辙,智商碾压题。楼主没遇到之前就只会这种做法。

public int singleNumber(int[] A) {
        Map<Integer, Integer> counters = new HashMap<>();
        for(int i = 0; i < A.length; i++) {
            if (!counters.containsKey(A[i])) {
                counters.put(A[i], 1);
            } else {
                counters.put(A[i], counters.get(A[i]) + 1);
            }
        }
        
        for (Integer key : counters.keySet()) {
            if (counters.get(key) == 1) {
                return key;
            }
        }
        throw new RuntimeException("no single number");
    }

而后我们知道可以先声明个长度32的整形数组,int[32]。第i个元素存放“这些整数第i位的1的个数除以三的余数”。好拗口是不是?

public int singleNumber2(int[] A) {
        int[] counter = new int[32];
        int ret = 0;
        for(int i = 0; i < 32; i++) {
            for (int j = 0; j < A.length; j++) {
                counter[i] += (A[j] >> i) & 1;
            }
            ret |= (counter[i] % 3) << i;
        }
        return ret;
    }

看了代码其实也不是“不明觉厉”。因为assume只有一个数出现一次,其他都出现3次,那么那个single number的第i位就是余下的那个数。

。。。

楼主中文不好。

btw,还有一个不是很直观的位操作方法。贴这里吧,不过没做过这个的感觉很难想到。

http://oj.leetcode.com/discuss/857/constant-space-solution 

posted on 2015-02-27 21:29  lichen782  阅读(1987)  评论(0编辑  收藏  举报