【一天一道LeetCode】#31. Next Permutation

本文详细解析了LeetCode上的一道经典题目“下一个排列”。通过分析题目要求,给出了清晰的解题思路,并提供了完整的C++代码实现。文章还介绍了next_permutation算法思想,包括寻找破坏升序的值、交换元素及后续数列的反转等步骤。

一天一道LeetCode系列

(一)题目

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

(二)解题


/*

本题用到STL中next_Permutation的思想:

(1)首先从右到左找到第一个破坏升序的值a,

(2)然后再从右至左找到第一个比a大的数b,

(3)交换a和b,

(4)再把交换后的a的位置之后的数反转。

如1,4,5,3,1

第一步找到4,第二步找到5,交换4,5得到15431,然后反转5以后的数,得到15134即为所求。

*/

class Solution {

public:

    void nextPermutation(vector<int>& nums) {

        int len = nums.size();

        if(len!=1){

            int i = len-2;

            while(i>=0 &&nums[i]>=nums[i+1]) i--;

            int j =len-1;

            while(j>i &&nums[j]<=nums[i]) j--;

            if(i>=0) swap(nums[i],nums[j]);

            reverse(nums.begin()+i+1,nums.end());

        }

    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值