【每日一题Day82】LC1806还原排列的最少操作步数 | 模拟

给定一个偶数整数,初始时有一个大小为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恢复到初始值所需的最少非零操作数。

还原排列的最少操作步数【LC1806】

You are given an even integer n. You initially have a permutation perm of size n where perm[i] == i (0-indexed).

In one operation, you will create a new array arr, and for each i:

  • If i % 2 == 0, then arr[i] = perm[i / 2].
  • If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].

You will then assign arr to perm.

Return the minimum non-zero number of operations you need to perform on perm to 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)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值