Skip to content

Commit 89f02e5

Browse files
committed
feat: add solutions to lc problem: No.1238
No.1238.Circular Permutation in Binary Representation
1 parent c2eee95 commit 89f02e5

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

Diff for: solution/1200-1299/1238.Circular Permutation in Binary Representation/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,34 @@
4444

4545
<!-- 这里可写通用的实现逻辑 -->
4646

47+
**方法一:二进制码转格雷码**
48+
49+
我们观察题目中的排列,可以发现,它的二进制表示中,任意两个(包括首尾)相邻的数只有一位二进制数不同。这种编码方式就是格雷码,它是我们在工程中会遇到的一种编码方式。
50+
51+
二进制码转换成二进制格雷码,其法则是保留二进制码的最高位作为格雷码的最高位,而次高位格雷码为二进制码的高位与次高位相异或,而格雷码其余各位与次高位的求法相类似。
52+
53+
假设某个二进制数表示为 $B_{n-1}B_{n-2}...B_2B_1B_0$,其格雷码表示为 $G_{n-1}G_{n-2}...G_2G_1G_0$。最高位保留,所以 $G_{n-1} = B_{n-1}$;而其它各位 $G_i = B_{i+1} \oplus B_{i}$,其中 $i=0,1,2..,n-2$。
54+
55+
因此,对于一个整数 $x$,我们可以用函数 $gray(x)$ 得到其格雷码:
56+
57+
```java
58+
int gray(x) {
59+
return x ^ (x >> 1);
60+
}
61+
```
62+
63+
我们可以直接将 $[0,..2^n - 1]$ 这些整数映射成对应的格雷码数组,然后找到 $start$ 在格雷码数组中的位置,将格雷码数组从该位置开始截取,再将截取的部分拼接到格雷码数组的前面,就得到了题目要求的排列。
64+
65+
时间复杂度 $O(2^n)$,其中 $n$ 为题目给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。
66+
67+
**方法二:转换优化**
68+
69+
由于 $gray(0) = 0$,那么 $gray(0) \oplus start = start$,而 $gray(i)$ 与 $gray(i-1)$ 只有一个二进制位不同,所以 $gray(i) \oplus start$ 与 $gray(i-1) \oplus start$ 也只有一个二进制位不同。
70+
71+
因此,我们也可以直接将 $[0,..2^n - 1]$ 这些整数映射成对应的 $gray(i) \oplus start$,即可得到首项为 $start$ 的格雷码排列。
72+
73+
时间复杂度 $O(2^n)$,其中 $n$ 为题目给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。
74+
4775
<!-- tabs:start -->
4876

4977
### **Python3**
@@ -161,6 +189,18 @@ func circularPermutation(n int, start int) (ans []int) {
161189
}
162190
```
163191

192+
### **TypeScript**
193+
194+
```ts
195+
function circularPermutation(n: number, start: number): number[] {
196+
const ans: number[] = [];
197+
for (let i = 0; i < 1 << n; ++i) {
198+
ans.push(i ^ (i >> 1) ^ start);
199+
}
200+
return ans;
201+
}
202+
```
203+
164204
### **...**
165205

166206
```

Diff for: solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md

+12
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,18 @@ func circularPermutation(n int, start int) (ans []int) {
164164
}
165165
```
166166

167+
### **TypeScript**
168+
169+
```ts
170+
function circularPermutation(n: number, start: number): number[] {
171+
const ans: number[] = [];
172+
for (let i = 0; i < 1 << n; ++i) {
173+
ans.push(i ^ (i >> 1) ^ start);
174+
}
175+
return ans;
176+
}
177+
```
178+
167179
### **...**
168180

169181
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
function circularPermutation(n: number, start: number): number[] {
2+
const ans: number[] = [];
3+
for (let i = 0; i < 1 << n; ++i) {
4+
ans.push(i ^ (i >> 1) ^ start);
5+
}
6+
return ans;
7+
}

0 commit comments

Comments
 (0)