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

分析

关于字典序的概念其实我并不是很清楚,所以首先从小到大列出了{1,2,3}的6中排列方式,总结了其变化规律,具体见代码。

实现一

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n=nums.size();
        if(n<2) return;
        int i=n-2, j;
        while(i>=0){
            int j=n-1;
            while(j>i && nums[i]>=nums[j])
                j--;
            if(j>i){
                swap(nums[i], nums[j]);
                sort(nums.begin()+i+1, nums.end());
                break;
            }
            i--;
        }
        if(i<0)
            sort(nums.begin(), nums.end());
    }
};

思考一

本来也不打算重构了,虽然代码有点丑。但是后面看题解发现有O(n)的解法,决定还是搞一搞。
一个是由后往前搜索大数的时候如果前一次不成功,就已经保证了之前的数字是降序的,利用这个可以较少比较次数。另外sort也是不必要的,swap之后的子数组保证了是降序的,直接reverse成升序就行了。

实现二

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n=nums.size();
        if(n<2) return;
        int i=n-2;
        while(i>=0 && nums[i]>=nums[i+1])
            i--;
        if(i<0){
            reverse(nums.begin(), nums.end());
        }
        else{
            int j=n-1;
            while(nums[j]<=nums[i])
                j--;
            swap(nums[i], nums[j]);
            reverse(nums.begin()+i+1, nums.end());
        }
    }
};

思考二

提交通过之后发现成绩并没有提高。。。我的内心是崩溃的,只能说这个平台很诡异。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Implement next permutation, which rearranges numbers into...
    stevewang阅读 530评论 0 0
  • tags: Array Implement next permutation, which rearranges ...
    江米条二号阅读 801评论 0 0
  • 问题描述 Implement next permutation, which rearranges numbers...
    codingXue阅读 259评论 0 0
  • 过了许多年,我还是不太习惯用闺蜜来形容她,我更喜欢用好友来称呼她。 在这世界上,有人惊艳了你的时光,有人却...
    杨卷阅读 285评论 2 1
  • 风起兮,送诸君以征沙场 风猎猎,击燮鼓以振山河 今,乘杀伐之风,破敌国之军 待归来之日,狂饮敌虏之血,侧身醉卧于沙...
    梵夜阅读 253评论 0 2