【Leet Code】31. Next Permutation---Medium

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

思路:

1)从最右边向左边遍历,找到第一个左边的数小于右边的数的位置fir;

2)如果fir==0,则说明原来数据是从大到小排序的,此时将整个数组翻转即可;

3)否则,先--fir,令fir指向第一个需要被交换的数,然后从右向左遍历找到第一个比fir的值大的数的位置sec,交换fir和sec的值,将fir后面的数据从小到大排序。


代码实现:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
    int fir = nums.size() -1, sec = nums.size() -1;
    
    //先找到第一个比前面比后面大的数的位置。如[4,2, 0, 2, 3, 2, 0]里面2,3值2<3
    while(fir > 0 && nums[fir] <= nums[fir - 1]) --fir;

    //如果是最大数,即题目中的If such arrangement is not possible, it must rearrange it as the lowest possible order成立
    if(fir == 0)
    {
        reverse(nums.begin(), nums.end());
        return;
    }
    
    --fir; //令fir指向第一个要被交换的元素
    while(sec > fir && nums[sec] <= nums[fir]) --sec;
    swap(nums[fir], nums[sec]);
    
    //将新交换位置后面的所有数字从小到大排序
    sort(nums.begin()+fir+1, nums.end());
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值