您的位置:首页 > 其它

leetcode 31 -- Next Permutation

2015-06-15 18:52 525 查看

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

题意:

全排列问题,用过c++STL的next_permutation的都用该知道。

给定一个序列,找到该序列排序的下一个序列,要求不能使用额外的空间。

题目也给例子了比如1,2,3的下一个排列是1,3,2。

思路:

如果是按照题目从小到大顺序,我们应该先从后往前找到满足向另元素顺序为小于顺序的第一对元素a[i] < a[i+1],因为我们所找到的第一个a[i]正是我们下一次全排列的需要交换的元素之一,比如1,4,3,2,a[i]就是1 (有点类似进位的感觉),接着从末尾找到第一个比a[i]大的元素a[j],在1,4,3,2中是2,也就是次小于1的,然后交换a[i]和a[j],此时序列变为2,4,3,1,因为交换完1,2后,此刻为2开头最小的全排列,所以排序2后面的所有数字(从小到大),变为2,1,3,4,还是类似进位的感觉。

代码:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size() < 2){
            return;
        }
        int i,j;
        //找i
        for(i = nums.size()-2; i >= 0; --i){
            if(nums[i] < nums[i+1]){
                break;
            }
        }
        //找j
        for(j = nums.size()-1; j > i; --j){
            if(nums[i] < nums[j]){
                break;
            }
        }
        int t;
        //交换i,j
        if(i >= 0){
            t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
        //原本我们因该排序,找j时是nums[i]<nums[j],后面的元素是有序的,只不过是逆序,我们reverse即可。不过sort也AC了
        //sort(nums.begin()+i+1, nums.end());
        reverse(nums.begin()+i+1, nums.end());
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: