leetcode1806: The minimum number of steps to restore the arrangement (one question per day on 1.9 days)

Topic statement:

Given an even number n​​​​​​​, it is known that there exists a perm perm of length n, where perm[i] == i​(subscripts start counting from 0).

In one step, you create a new array arr, 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]
Then the arr​​ Assigned to perm.

What is the minimum number of steps required to bring perm back to the original permutation? Returns the smallest non-zero number of operation steps.

Example 1:

Input: n = 2
Output: 1
Explanation: Initially, perm = [0,1]
After step 1, perm = [0,1]
So, only 1 step is required
Example 2:

Input: n = 4
Output: 2
Explanation: Initially, perm = [0,1,2,3]
After step 1 operation, perm = [0,2,1,3]
After step 2 operation, perm = [0 ,1,2,3]
So, only 2 steps are required
Example 3:

Input: n = 6
Output: 4
 

hint:

2 <= n <= 1000
n​​​​​​ is an even number

Problem-solving ideas:

        Seeing that the maximum value range of n is only 1000, there are many solutions to this problem.

        One is the mathematical solution. Only the code for solving the problem is given below, so I won't go into it further!

        The other is a simple simulation situation, which simulates all situations until it is the same as the original array perm, and calculates the number of simulation situations. It should be noted that the original array needs to be assigned to a new array, and this is used to compare whether the original array is the same as the new array, and return if they are the same.

Problem-solving code (mathematics):

class Solution {
public:
    int reinitializePermutation(int n) {
        if (n == 2) {
            return 1;
        }
        int step = 1, pow2 = 2;
        while (pow2 != 1) {
            step++;
            pow2 = pow2 * 2 % (n - 1);
        }
        return step;
    }
};

Problem-solving code (simulation):

class Solution {
public:
    int reinitializePermutation(int n) {
        vector<int>perm(n,0);
        vector<int>arr(n,0);
        int cnt=0;
        for(int i=0;i<n;i++)
        {
            perm[i]=i;
        }
        vector<int>path;
        path.assign(perm.begin(),perm.end());
        while(arr!=path)
        {
            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];
                }
            }
            cnt++;
            perm.assign(arr.begin(),arr.end());
        }
        return cnt;
    }
};

        This question is a simple question, and it feels difficult to increase n by 1e9! ! !

Guess you like

Origin blog.csdn.net/m0_63743577/article/details/128618359