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 1734. Decode XORed Permutation #204

Open
Woodyiiiiiii opened this issue Feb 3, 2023 · 0 comments
Open

Leetcode 1734. Decode XORed Permutation #204

Woodyiiiiiii opened this issue Feb 3, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Feb 3, 2023

类似题目:

这道题我想到了^的交换律,从而想到了只要求出数组内任意一个数,就可以求出全部数组,然而没想到如何求出一个数。因为我漏看了条件

首先,XOR的交换律,即a^b=c就有a^c=bb^c=a。这也是之前写swap方法(交换两个数)能够用XOR的原因。

然后,注意到题目中,数组是1~n的任意permutation。所以,对于a0,我们可以通过encoded[1],encoded[3]...得到a1^a2,a3^a4...得到其他所有的XOR结果,从而提前用1~n的所有XOR结果去XOR除a0外的XOR结果,得到a0,从而推出数组所有元素。

class Solution {
    public int[] decode(int[] encoded) {
        int sum = 0;
        for (int i = 1; i <= encoded.length + 1; ++i) {
            sum ^= i;
        }
        int others = 0;
        for (int i = 1; i < encoded.length; i += 2) {
            others ^= encoded[i];
        }
        int a = sum ^ others;
        int[] ans = new int[encoded.length + 1];
        ans[0] = a;
        for (int i = 1; i < ans.length; ++i) {
            ans[i] = encoded[i - 1] ^ a;
            a = ans[i];
        }
        return ans;
    }
}

@Woodyiiiiiii Woodyiiiiiii changed the title Leetcode 2527. Find Xor-Beauty of Array Leetcode 1734. Decode XORed Permutation Feb 7, 2023
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