Leetcode -- 31. Next Permutation

题目:

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


思路:这道题还是有点难度的,参考了别人的思路,解法如下:

6,8,7,4,3,2为例:
这里写图片描述

  1. 首先从后往前遍历,找到第一个不按递增排列的元素,即nums[i-1],上图中的6。
  2. 再从后往前,找到第一个比nums[i-1] 大的元素,即nums[j] , 上图中的7。
  3. 交换nums[i-1]nums[j] 的位置,变成7, 8, 6, 4, 3, 2
  4. i → nums.size()-1 的元素进行排序, 变成:7, 2, 3, 4, 6, 8

C++代码如下:

void nextPermutation(vector<int>& nums) {
        if (nums.size() <= 1)
            return;
        int right = nums.size() - 1;
        int i = right,j = right,temp;

        while (nums[i] <= nums[i - 1]) {
            --i;
        }
        if (i == 0) {
            sort(nums.begin(), nums.end());
            return;
        }


        while (nums[i-1] >= nums[j])
        {
            --j;
        }

        temp = nums[j];
        nums[j] = nums[i-1];
        nums[i-1] = temp;

        sort(nums.begin() + i,nums.end());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值