31-NextPermutation

题目:

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

分析:

这个题目是一组数字进行全排列,然后找到其中一个序列的下一个序列
NextPermutation 序列所组成的数字比上一个大,一个逆序排列的数组没有下一个排列。
主要是两个Flag

  • step 1. 从右向左找到第一个比i+1 位置的数字小的i
  • step 2. 从右向左找到第一个比nums[i] 大的数字nums[j](这里我采用的是从左向右)
  • step 3. swap(nums,i,j)
  • step 4. 将i+1 ~end 的数字进行逆序
代码:
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int len = nums.size();
        int i = len - 2;
        while ((i >= 0) && (nums[i] >= nums[i + 1]))
        {
            i--;
        }
        int j = i+1;
        if (i >= 0)
        {
            while (j < len&&nums[j]>nums[i])
            {
                j++;
            }
            swap(nums, i, j-1);
        }
        reverse(nums, i + 1);

    }
    void reverse(vector<int>& nums, int start)
    {
        int end = nums.size()-1;
        while (start < end)
        {
            swap(nums, start, end);
            start++;
            end--;
        }
    }
    void swap(vector<int>& nums, int i, int j)
    {
        int tmp = 0;
        tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值