Leetcode - Single Num II

[分析]
此题找到三种符合题意的解法,只理解了解法1,解法2有很详细的解析,理解中~
解法1:对于32个数位,遍历数组统计每一位上 1 出现的次数,若 mod 3为1说明仅出现一次的数字该位为1。该解法可简单套用到变形题目:除1个数字外其余均出现k次。
注意此题可一般化为: 给定一个数组,除了一个数出现 k 次外其他数字均出现 p 次,其中 p > 1, k >= 1, p % k != 0, 求那个出现 k 次的数字。解法2思路可解。

感谢yb君耐心详细解释,并分享理解代码的有效方法~ 代入建立例子一步步执行代码非常有助于理解,尤其是这么精短的代码。
对于singleNumber2
  twos  ones  mask ones  twos
1  0      1     1    1     0
1  1      0     1    0     1
1  1      1     0    0     0
1  0      1     1    1     0
对于singleNum
  one two
1  1   0
1  0   1
1  0   0
1  1   0
对当前的我来说,文字解释还是非常有助于我理解代码的,leetcode的那篇解析还是非常不错,他试图解释思路是怎么一步步形成的。现在基本理解了后两种方法的正确性,但自己是万万想不出这么巧妙的位运算技巧的~

[ref]
http://blog.csdn.net/kenden23/article/details/13625297
http://www.cnblogs.com/daijinqiao/p/3352893.html
https://leetcode.com/discuss/6632/challenge-me-thx
解法2非常详尽的解析
https://leetcode.com/discuss/31595/detailed-explanation-generalization-bitwise-operation-numbers

public class Solution {
    public int singleNumber1(int[] nums) {
        int ret = 0;
        for (int i = 0; i < 32; i++) {
            int counter = 0;
            for (int num : nums) {
                if (((num >> i) & 1) == 1)
                    counter++;
            }
            if (counter % 3 == 1)
                ret |= (1 << i);
        }
        return ret;
    }
    // the masks will be 0 only when the counter reaches k and be 1 for all other count cases
    public int singleNumber2(int[] nums) {
        int ones = 0, twos = 0, mask = 0;
        for(int num : nums) {
            twos |= (ones & num);
            ones ^= num;
            mask = ~(ones & twos);
            ones &= mask;
            twos &= mask;
        }
        return ones;
    }
    public int singleNumber(int[] nums) {
        int ones = 0, twos = 0;
        for(int num : nums) {
            ones = (ones ^ num) & ~twos;
            twos = (twos ^ num) & ~ones;
        }
        return ones;
    }
}

猜你喜欢

转载自likesky3.iteye.com/blog/2235893