Skip to content

Leetcode 2527. Find Xor-Beauty of Array #168

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

Open
Woodyiiiiiii opened this issue Jan 7, 2023 · 0 comments
Open

Leetcode 2527. Find Xor-Beauty of Array #168

Woodyiiiiiii opened this issue Jan 7, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jan 7, 2023

这道题是双周赛第三题。

一开始我也没有头绪,最后观察题目给的第二个用例,用Map存取结果后,发现出现偶数次的数可以用^约去,于是直接得出了结果。

竞赛完后回想,显然,这是要找规律化简式子的。

所以可以从用例入手,比如题目给出的[1,4],可以发现如下关键线索:

  1. 最后的 ^异或符号,可以想到偶数次数的同一个数异或为0
  2. 利用&和|的交换律

所以最后所有复杂的式子约去,只剩下所有元素本身。

class Solution {
    public int xorBeauty(int[] nums) {
        int ans = 0;
        for (int num : nums) {
            ans ^= num;
        }
        return ans;
    }
}

有意思的位运算。


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