还原排列的最少操作步数
难度:
标签:
题目描述
代码结果
运行时间: 30 ms, 内存: 16.0 MB
/*
* Problem: Given an even number n, there exists a permutation perm of length n
* where perm[i] == i (0-indexed). In one step, a new array arr is created as follows:
* - If i % 2 == 0, then arr[i] = perm[i / 2]
* - If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]
* The task is to find the minimum number of steps to return perm back to its original state.
*
* Solution using Java Streams:
* - Initialize perm with values 0 to n-1.
* - Create arr using stream operations for each transformation.
* - Keep track of steps until the permutation is restored.
*/
import java.util.Arrays;
import java.util.stream.IntStream;
public class Solution {
public int reinitializePermutation(int n) {
int[] perm = IntStream.range(0, n).toArray();
int steps = 0;
int[] arr = new int[n];
while (true) {
steps++;
arr = IntStream.range(0, n).map(i -> i % 2 == 0 ? perm[i / 2] : perm[n / 2 + (i - 1) / 2]).toArray();
if (Arrays.equals(arr, IntStream.range(0, n).toArray())) break;
perm = arr;
}
return steps;
}
}
解释
方法:
此题解侧重于追踪一个特定位置上的元素在操作过程中的移动。具体来讲,题解追踪了初始时索引为1的元素,观察这个元素如何通过给定的操作回到起始位置。算法通过模拟指定的操作,即在偶数索引时将元素置于索引的一半位置,而在奇数索引时则移动到n/2加上索引减一再除以二的位置,来确定元素回到起始位置所需的最小步数。这种方法有效地利用了循环的特性,即特定元素的运动轨迹会形成一个闭环。通过不断执行操作并记录步数,直到该元素回到初始位置,从而得到结果。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么选择追踪索引为1的元素而不是其他索引的元素来确定算法的结束条件?
▷🦆
在算法描述中提到,循环直到元素回到初始位置。这种方法是否意味着只有跟踪的那个元素回到起始位置就足够了,还是说需要验证所有元素都必须回到起始位置?
▷🦆
题解中提到的操作步骤在奇数索引时使用了表达式 `n // 2 + (index - 1) // 2`,这个表达式的具体含义是什么?它是如何确保元素正确移动的?
▷