Under the arrangement [a] [LeetCode find the law]

Achieve a function of the acquired arrangement, a given algorithm requires rearranging the sequence number next in lexicographically larger arrangement.

If the next larger arrangement does not exist, the smallest number of rearranged alignment (i.e., ascending order).

You must place editing, allowing only constant additional space.

The following are some examples, the input column on the left, on the right column the corresponding output.
→ 1, 3,2, 2, 3
3,2,1 →, 2, 3
1,1,5 1,5,1 →

Source: stay button (LeetCode)
link:
https://leetcode-cn.com/problems/next-permutation

analysis:

Method 1: Direct transfer API, next_permutation function

ps: I do not recommend this approach

Method 2: find the law

1. First, find the highest index k, satisfies v [k] <v [k + 1], and if not, it indicates that the current sequence is the sequence 54321, 12345 which is the next sequence, flipped direct entire array

2. Further to find a maximum index L, satisfies v [L]> v [k]

3. exchange v [L] and v [k]

4. Turn v [k + 1, end]

To sum up in one sentence: forward traversing find the first descending from the value x, and then from the back to find the first value is greater than the value of y, swap the two values, the values ​​behind the last of the reversal of values to

Time complexity: O (N)

Space complexity: O (. 1 )

class Solution {
public:
void nextPermutation(vector<int>& v)
{
    int n=v.size();
    if(n==1)
        return ;
    int flag=0;
    int k;
    for(int i=n-2; i>=0; i--)
    {
        if(v[i]<v[i+1])
        {
            flag=1;
            k=i;
            cout<<k<<endl;
            break;
        }
    }
    if(flag==0)
    {
        reverse(v.begin(),v.end());
        return ;
    }
    int l;
    int x=v[k];
    for(int i=n-1; i>=k; i--)
    {
        if(v[i]==x)
        {
            l=i;
            x=v[i];
        }else if(v[i]>x)
        {
            l=i;
            break;
        }
    }
    swap(v[k],v[l]);
    reverse(v.begin()+k+1,v.end());
}
};

Guess you like

Origin www.cnblogs.com/yinbiao/p/11348134.html