1238. 循环码排列
Tag Math
Difficulty Medium
Link https://leetcode-cn.com/problems/circular-permutation-in-binary-representation/
分析
根据89题格雷码可以得知二进制与格雷码之间有这样的规律:
假设格雷码第n位为G(n), 二进制第n位为B(n)
对于n+1位,
G ( n + 1 ) = B ( n + 1 ) G(n+1) = B(n+1) G(n+1)=B(n+1)
G ( n ) = B ( n + 1 ) X O R B ( n ) G(n) = B(n+1) XOR B(n) G(n)=B(n+1)XORB(n)
那么在本题中,我们可以先根据n生成 2 n 2^n 2n个格雷码,然后找到start所在的位置,重新排列。
题解
class Solution {
public List<Integer> circularPermutation(int n, int start) {
List<Integer> list = new ArrayList<>();
int index = 0;
for (int i=0; i<1<<n; i++) {
list.add(i^i>>1);
// 获取start所在的位置
if ((i^i>>1) == start) {
index = i;
}
}
// 重新排列数组,从start开始
List<Integer> res = new ArrayList<>();
res.addAll(list.subList(index, list.size()));
res.addAll(list.subList(0, index));
return res;
}
}
复杂度分析
-
时间复杂度:
O(2^n)
-
空间复杂度:
O(1)