Next Permutation(寻找字典序比输入大1的序列)

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,31,3,2
3,2,11,2,3

1,1,51,5,1


题目解读:

题目的意思是在原序列的基础上,寻找一个比原序列在字典序上大 1 的新序列,如果没有找到(即原序列正好是非升序排列),则直接返回升序序列。


解题思路:

1. 要使得新序列刚好比原序列大 1 ,那么就是尽量在原序列的低位进行交换;

2. 以序列的倒数第二位开始(此处以 left 指针指出)作为可能的待交换点,从序列的末尾向前搜索(以 right 指针指出),寻找第一个大于这个可能交换点的值的数字;

3. 如果找到,则交换 left 和 right ,此时可以保证这个新序列比原序列大,但是不能保证正好大 1 ,所以对再 left 之后的元素进行排序,保证正好大 1;

4. 如果没找到,那么 left--,作为新的可能交换点,重复以上步骤。


完整代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <stack>

using namespace std;


#define MAX_INT (int)0x7FFFFFFF
#define MIN_INT (int)0x80000000
class Solution {
public:
 void nextPermutation(vector<int>& nums) {
        
     int right = nums.size()-1;
     int left = nums.size()-2;


     while(left >= 0) {
         right = nums.size()-1;
        
         while(right > left && nums[right] <= nums[left])right--;

         if(right != left) {
            int tmp = nums[left];
            nums[left] = nums[right];
            nums[right] = tmp;
            break;
         }
        left--;
     }
     sort(nums.begin()+left+1,nums.end());
 }
};

void main()
{
    int tmp[] = {1,2,4,3,5};
    Solution s;
    vector<int> nums(&tmp[0],&tmp[4]);
    s.nextPermutation(nums);
     //cout << <<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值