59
59
60
60
<!-- solution:start -->
61
61
62
- ### Solution 1
62
+ ### Solution 1: Bit Manipulation
63
+
64
+ Based on the problem description, we have:
65
+
66
+ $$
67
+ \text{encoded}[i] = \text{arr}[i] \oplus \text{arr}[i + 1]
68
+ $$
69
+
70
+ If we XOR both sides of the equation with $\text{arr}[ i] $, we get:
71
+
72
+ $$
73
+ \text{arr}[i] \oplus \text{arr}[i] \oplus \text{arr}[i + 1] = \text{arr}[i] \oplus \text{encoded}[i]
74
+ $$
75
+
76
+ Which simplifies to:
77
+
78
+ $$
79
+ \text{arr}[i + 1] = \text{arr}[i] \oplus \text{encoded}[i]
80
+ $$
81
+
82
+ Following the derivation above, we can start with $\text{first}$ and sequentially calculate every element of the array $\text{arr}$.
83
+
84
+ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array.
63
85
64
86
<!-- tabs:start -->
65
87
69
91
class Solution :
70
92
def decode (self , encoded : List[int ], first : int ) -> List[int ]:
71
93
ans = [first]
72
- for e in encoded:
73
- ans.append(ans[- 1 ] ^ e )
94
+ for x in encoded:
95
+ ans.append(ans[- 1 ] ^ x )
74
96
return ans
75
97
```
76
98
@@ -96,9 +118,10 @@ class Solution {
96
118
class Solution {
97
119
public:
98
120
vector<int > decode(vector<int >& encoded, int first) {
99
- vector<int > ans{{first}};
100
- for (int i = 0; i < encoded.size(); ++i)
101
- ans.push_back(ans[ i] ^ encoded[ i] );
121
+ vector<int > ans = {{first}};
122
+ for (int x : encoded) {
123
+ ans.push_back(ans.back() ^ x);
124
+ }
102
125
return ans;
103
126
}
104
127
};
@@ -109,13 +132,25 @@ public:
109
132
```go
110
133
func decode(encoded []int, first int) []int {
111
134
ans := []int{first}
112
- for i, e := range encoded {
113
- ans = append(ans, ans[i]^e )
135
+ for i, x := range encoded {
136
+ ans = append(ans, ans[i]^x )
114
137
}
115
138
return ans
116
139
}
117
140
```
118
141
142
+ #### TypeScript
143
+
144
+ ``` ts
145
+ function decode(encoded : number [], first : number ): number [] {
146
+ const ans: number [] = [first ];
147
+ for (const x of encoded ) {
148
+ ans .push (ans .at (- 1 )! ^ x );
149
+ }
150
+ return ans ;
151
+ }
152
+ ```
153
+
119
154
<!-- tabs: end -->
120
155
121
156
<!-- solution: end -->
0 commit comments