问题
有一个隐藏的整数数组 arr ,它 是由 n 非负的整数。它被编码为另一个 长度为的 整数数组 编码*n* - 1,这样 encoded[i] = arr[i] XOR arr[i + 1].
例如,如果 arr = [4, 2, 0, 7, 4``] 则 encoded = [6, 2, 7, 3].你得到了 编码后的 数组。还 先 给你一个整数 ,也就是 arr的第一个元素 , 即 arr[0].返回 原始数组arr.可以证明答案是存在的并且是唯一的。
处理方法
在这里我们可以利用XORing的特性。如果,对于一些整数 a, b 和 c。
*a* ^ *b* = *c*,那么 *b* = *a* ^ *c*.使用这种方法,由于原始数组的第一个元素已经给出,解码后的数组的下一个元素是decoded[0] ^ encoded[0] 。我们可以对其余的元素进行类似的操作,对整个数组进行解码。这种方法的时间复杂度为O(N)。
C++编程
#include<bits/stdc++.h>
using namespace std;
//function to return decoded array
vector<int> decode(vector<int>& encoded, int first) {
vector<int>decoded;
int n = encoded.size();
decoded.push_back(first); //first element is given
for(int i=0;i<n;i++){
decoded.push_back(decoded[i]^encoded[i]); //find next element
}
return decoded;
}
int main(){
vector<int>encoded{6, 2, 7, 3};
int first = 4;
vector<int>ans = decode(encoded, first);
for(auto itr: ans) cout<<itr<<" ";
}
输出
4 2 0 7 4
Python编程
#function to decode array
def decode(a, first):
a=[]
a.append(first) #first element is given to us
x=first
for i in encoded:
x^=i #find next element
a.append(x)
return a
encoded = [6, 2, 7, 3]
first = 4
print(decode(encoded, first))
输出
[4, 2, 0, 7, 4]
C语言编程
#include<stdio.h>
//function to return decoded array
void decode(int encoded[], int first) {
int decoded[5];
decoded[0] = first; //first element is given
for(int i=0;i<4;i++){
decoded[i+1] = decoded[i]^encoded[i]; //find next element
}
for(int i=0;i<5;i++){
printf("%d ", decoded[i]);
}
}
int main(){
int encoded[4] = {6, 2, 7, 3};
int first = 4;
decode(encoded, first);
}
输出
4 2 0 7 4