还原排列的最少操作步数【LC1806】
You are given an even integer
n. You initially have a permutationpermof sizenwhereperm[i] == i(0-indexed).In one operation, you will create a new array
arr, and for eachi:
- If
i % 2 == 0, thenarr[i] = perm[i / 2].- If
i % 2 == 1, thenarr[i] = perm[n / 2 + (i - 1) / 2].You will then assign
arrtoperm.Return the minimum non-zero number of operations you need to perform on
permto return the permutation to its initial value.
数学就算了 不要为难自己
-
思路:按照题意进行变换,直至数组变为原始数组,记录变换次数
-
实现
class Solution { public int reinitializePermutation(int n) { int[] perm = new int[n]; int[] arr = new int[n]; for (int i = 0; i < n; i++) perm[i] = i; for (int i = 0; i < n; i++){ if (i % 2 == 0){ arr[i] = perm[i / 2]; }else{ arr[i] = perm[n / 2 + (i - 1) / 2]; } } int count = 1; while (!Arrays.equals(perm, arr)){ int[] tmp = new int[n]; for (int i = 0; i < n; i++){ if (i % 2 == 0){ tmp[i] = arr[i / 2]; }else{ tmp[i] = arr[n / 2 + (i - 1) / 2]; } } for (int i = 0; i < n; i++) arr[i] = tmp[i]; count++; } return count; } }- 复杂度
- 时间复杂度:O(n2)O(n^2)O(n2)
- 空间复杂度:O(n)O(n)O(n)
- 复杂度
-
好看的代码
class Solution { public int reinitializePermutation(int n) { int[] prem = new int[n], arr = new int[n]; for (int i = 0; i < n; i++) prem[i] = i; int i, step = 1; while (true) { for (i = 0; i < n; i++) arr[i] = i % 2 == 0 ? prem[i / 2] : prem[(n - 1 + i) / 2]; for (i = 0; i < n && arr[i] == i; i++); if (i == n) return step; for (i = 0; i < n; i++) prem[i] = arr[i]; step++; } } } 作者:Tizzi 链接:https://leetcode.cn/problems/minimum-number-of-operations-to-reinitialize-a-permutation/solutions/2052353/liang-chong-jie-fa-mo-ni-mo-ni-you-hua-b-2ijm/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

给定一个偶数整数,初始时有一个大小为n的排列perm,其中perm[i]==i(0索引)。每次操作,你会创建一个新的数组arr,对于每个i:如果i%2==0,则arr[i]=perm[i/2];否则,arr[i]=perm[n/2+(i-1)/2]。然后将arr分配给perm。返回使perm恢复到初始值所需的最少非零操作数。
1万+

被折叠的 条评论
为什么被折叠?



