Leetcode 1734: 解码异或后的排列 Decode XORed Permutation

中文描述:

给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。
它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。
给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。

题目描述:

There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.

It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].

Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.

Example 1:

Input: encoded = [3,1]
Output: [1,2,3]
Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]

Example 2:

Input: encoded = [6,5,4,6]
Output: [2,4,1,5,3]

Constraints:

3 <= n < 105
n is odd.
encoded.length == n - 1

Time complexity: O O O( N N N)
Space complexity: O O O( N N N)
位运算 XOR:
根据异或位运算的性质:

  1. 归零律:a ⊕ a = 0
  2. 恒等律:a ⊕ 0 = a
  3. 自反律:a ⊕ b ⊕ a = b.
    注意到原perm数组的长度位奇数,则我们可以把除第一个数 perm[0] 以外的数两两配对,找出它们的异或和 计为 xsum, 即encoded 数组中index 为奇数的异或和。
    e.g encoded = [6,5,4,6], perm = [2,4,1,5,3]。 除了perm[0] = 2 以外:
    perm[1] ⊕ perm[2] = 4 ⊕ 1 = 5 = encoded[1];
    perm[3] ⊕ perm[4] = 5 ⊕ 3 = 6 = encoded[3].
    xsum = 5 ⊕ 6 = 3
    再求出原perm数组中n个数的异或和 e.g: sum = 1 ⊕ 2 ⊕ 3 ⊕ 4 ⊕ 5 = 1.
    则根据3自反律第一个数 perm[0] = sum ⊕ xsum = 1。
    得到第一个数后,我们可以根据自反律,从左往右遍历啊 encoded 得到原数组。
    已知 a = perm[i],c = encoded[i] = perm[i] ⊕ perm[i + 1] . 我们已知 a 和 c 则:
    a⊕c = perm[i] ⊕ perm[i] ⊕ perm[i + 1] = perm[i + 1].
class Solution {
    public int[] decode(int[] encoded) {
        int n = encoded.length+1;
        int[] res = new int[n];
        int sum = 0;
        for(int i = 1; i <= n; i++){
            sum ^= i;
        }
        int num1 = sum;
        for(int i = 1; i < n-1; i+=2){
            num1 ^= encoded[i];
        }
        res[0] = num1;
        for(int i = 0; i < n-1; i++){
            res[i+1] = res[i]^encoded[i];
        }
        
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值