Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jaredliw opened this issue Jul 23, 2021 · 0 comments
Open

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

jaredliw opened this issue Jul 23, 2021 · 0 comments

Comments

@jaredliw
Copy link
Contributor

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 里,速度也比其他的方法快好多。

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant