LeetCode-31. 下一个排列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l718531794/article/details/85079658

题目地址:https://leetcode-cn.com/problems/next-permutation/
思路:第一种 STL提供了直接的函数,这里不赘述。要求字典序最小,那么尽可能我们去修改靠后的数字。于是从后往前,找第一个能被较大值替换的值,然后将它与之后比他大的最小值交换,再将其后所有数字从小到大排列即可。
AC代码:

class Solution {
public:
       
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        int maxx = nums[n-1];
        int flag = -1;
        for(int i = n-2;i>=0;i--){
            if(maxx>nums[i]){
                for(int j = n-1;j>i;j--){
                    if(nums[j]>nums[i]){
                        int temp = nums[j];
                        nums[j] = nums[i];
                        nums[i] = temp;
                        break;
                    }
                }
                flag = i;
                break;
            }
           if(maxx<nums[i])
               maxx = nums[i];
        }
        sort(nums.begin()+flag+1,nums.end());
    }
};

猜你喜欢

转载自blog.csdn.net/l718531794/article/details/85079658