[每日一题]1806.还原排列的最少操作步数

1806. 还原排列的最少操作步数 给你一个偶数 n ,已知存在一个长度为 n 的排列 perm ,其中 perm[i] == i(下标 从 0 开始 计数)。

一步操作中,你将创建一个新数组 arr ,对于每个 i :

  • 如果 i % 2 == 0 ,那么 arr[i] = perm[i / 2]
  • 如果 i % 2 == 1 ,那么 arr[i] = perm[n / 2 + (i - 1) / 2],然后将 arr 赋值给 perm 。

要想使 perm 回到排列初始值,至少需要执行多少步操作?返回最小的 非零 操作步数。字符串 pref 。返回 words 中以 pref 作为 前缀 的字符串的数目。字符串 s 的 前缀 就是 s 的任一前导连续字符串。

Solution

import java.util.Arrays;
class Solution {
    public int reinitializePermutation(int n) {
        int[] perm = new int[n];
        for (int i = 0; i < n; i++) {
            perm[i] = i;
        }

        int[] copy = Arrays.copyOf(perm, n);
        int[] temp = new int[n];
        int ans = 0;
        while (true) {
            for (int i = 0; i < n; i++) {
                if (i % 2 == 0) {
                    temp[i] = copy[i / 2];
                } else {
                    temp[i] = copy[n / 2 + (i - 1) / 2];
                }
            }
            ans++;
            if (Arrays.equals(temp, perm)) {
                break;
            }
            copy = Arrays.copyOf(temp, n);
        }
        return ans;
    }
}