LintCode 190: Next Permutation II

博客围绕 Next Permutation II 问题展开,要将数字重排成字典序中下一个更大排列,若无法实现则排成最小排列。给出多个示例,还提出原地替换、不额外分配内存的挑战,并介绍了从后往前查找、交换和反转的解法,若数组为降序则反转整个数组。
  1. Next Permutation II
    中文English
    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).

Example
Example 1:

Input:1,2,3
Output:1,3,2
Example 2:

Input:3,2,1
Output:1,2,3
Example 3:

Input:1,1,5
Output:1,5,1
Challenge
The replacement must be in-place, do not allocate extra memory.

解法1:从后往前找,直到找到一个nums[i]>nums[i-1]。然后再从后往前找,找到第一个大于nums[i-1]的数nums[j]。然后swap(nums[i-1], nums[j]),然后reverse nums[i…n-1]。
注意:

  1. 如果i=0,说明整个数组为降序序列,如[3,2,1],此时reverse整个字符串即可。
    代码如下:
class Solution {
public:
    /**
     * @param nums: An array of integers
     * @return: nothing
     */
    void nextPermutation(vector<int> &nums) {
        int n = nums.size();
        if (n <= 1) return;
        int i = 0, j = 0;
        for (i = n - 1; i > 0; --i) {
            if (nums[i] > nums[i - 1]) break;
        }
        
        if (i == 0) {
            reverse(nums.begin(), nums.end());
            return;
        }
        
        for (j = n - 1; j > i; --j) {
            if (nums[j] > nums[i - 1]) break;
        }
        swap(nums[i - 1], nums[j]);
        reverse(nums.begin() + i, nums.end());        
    //    int p1 = i, p2 = n - 1;
    //    while(p1 < p2) {
    //        swap(nums[p1], nums[p2]);
    //        p1++; p2--;
    //    }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值