A lexicographically arranged next leetcode31

Digital lexicographic order is the ratio of the size of the

First think of a few examples 123_> 1321243-> 1324, 12453-> 12534

 

1. The non-discharge sequence is descending sequence

, 2. The two strings of the same length the same as the ratio of the size of the foregoing, a first comparison of different character lengths, and the more rearward than the original string more large small string of

Since no longer has descending row, and the smaller the impact on the character, so to find a first left descending sequence number (rearmost) A [i], due to the large overall lexicographically on the descending sequence than just his large digital switching

The original large order than at this time to get the dictionary, but by no means least. Rearrangement A [i + 1] - A [len-1], in ascending order. Thus obtained is larger than the minimum original string string.

 

then

1. backwards to find the A [i]

2. dichotomy found the number to be exchanged

3. exchange, remake

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() > 1) {
            int i;
            for (i = nums.size() - 2; i > 0 && nums[i] >= nums[i+1]; i--);
            
            if(i==0&&nums[i]>=nums[i+1]){
                reverse(nums.begin(), nums.end());
                return;
            }
            reverse(nums.begin() + i+1, nums.end());
            auto it = upper_bound(nums.begin() + i+1, nums.end(), nums[i]);
            swap(nums[i], *it);
        }
        return;
    }
};

 

Guess you like

Origin www.cnblogs.com/lqerio/p/11785894.html