leetcode.1734. 解码异或后的排列----巧妙的位运算

1734. 解码异或后的排列

给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。

它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。

给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。

示例 1:

输入:encoded = [3,1]
输出:[1,2,3]
解释:如果 perm = [1,2,3] ,那么 encoded = [1 XOR 2,2 XOR 3] = [3,1]
示例 2:

输入:encoded = [6,5,4,6]
输出:[2,4,1,5,3]
 

提示:

3 <= n < 105
n 是奇数。
encoded.length == n - 1

题解:

首先要知道的是异或运算有一个重要的性质,即具有可逆性

即对于1,2,3三个数,1和2异或后再和3异或与1先和3异或再跟2异或是一样的;

因此合理利用其可逆性我们就可以像leetcode.1720. 解码异或后的数组—位运算一样进行解题,但是我们发现还缺少了一个first,即perm的第一个元素是要知道的因此我们需要先求出perm的第一个元素。

即我们观察题目得知,题目专门告诉我们perm是有奇数个元素,那么我们就可以知道encoded是有偶数个元素;
并且由于此为排列,由排列的性质我们可以知道perm内部的元素为1到encoded+1 的整数的排列,因此我们可以求出perm所有元素的异或结果tar1
并且由前面我们得到的encoded数组有偶数个元素,以及encoded数组每一个元素得到的过程我们可以知道,将encoded数组所有下标为奇数的元素进行异或,即相当于将perm的除了第一个元素的所有元素进行异或,因此我们可以得到tar2
最后我们发现tar1 与 tar2 进行异或后即为我们想要的first,即perm[0],剩下的过程同leetcode.1720. 解码异或后的数组—位运算

代码(Java):

class Solution {
    public int[] decode(int[] encoded) {
        int[] res = new int[encoded.length+1];
        int tar1 = 0;
        int tar2 = 0;
        for(int i=1;i<=encoded.length+1;i++){
            tar1 ^= i;
        }

        for(int i=1;i<encoded.length;i+=2){
            tar2 ^= encoded[i];
        }
        res[0] = tar2^tar1;
        for(int i=1;i<encoded.length+1;i++){
            res[i] = res[i-1] ^ encoded[i-1];
        }
        return res;
    }
}

代码(C):

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* decode(int* encoded, int encodedSize, int* returnSize){
    int*res = (int*)malloc(sizeof(int)*(encodedSize+1));
    
    int tar1 = 0;
    int tar2 = 0;
    for(int i=1;i<=encodedSize+1;i++)
    {
        tar1 ^= i;
    }

    for(int i=1;i<encodedSize;i+=2)
    {
        tar2 ^= encoded[i];
    }
    res[0] = tar2^tar1;
    for(int i=1;i<encodedSize+1;i++)
    {
        res[i] = res[i-1] ^ encoded[i-1];
    }

    *returnSize = encodedSize+1;
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向光.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值