algorithm-base icon indicating copy to clipboard operation
algorithm-base copied to clipboard

Leetcode 137 只出现一次的数字 II 的另一种解法

Open jaredliw opened this issue 4 years ago • 0 comments
trafficstars

Leetcode官方提供了一种用 AND,XOR 和 NOT 的解法。代码如下:

class Solution {
    public int singleNumber(int[] nums) {
        int seenOnce = 0, seenTwice = 0;
        for (int num : nums) {
            seenOnce = ~seenTwice & (seenOnce ^ num);
            seenTwice = ~seenOnce & (seenTwice ^ num);
        }
        return seenOnce;
  }
}

这个算法设计得很巧妙,只出现一次的数会在 seenOnce 里,出现两次的在 seenTwice 里,速度也比其他的方法快好多。

我才疏学浅,看的有点脑壳疼,希望有哪位大哥大姐可以解释一下,一同加到这个仓库的文章里。谢谢。

jaredliw avatar Jul 23 '21 14:07 jaredliw