Next Permutation解题报告

Description:

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.

Example:

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

Link:

https://leetcode.com/problems/next-permutation/#/description

解题方法:

从后往前找,找到第一个 nums[p] < nums[p+1]的数的位置p。
再次从后往前找,找到第一个nums[c] > nums[p]的数的位置c。
交换两个位置的数,再将p之后的数都反序。

Tips:

直接用reverse函数实现反序。

Time Complexity:

O(N)

完整代码:

void nextPermutation(vector<int>& nums) 
    {
        int n = nums.size();
        if(n < 2)
            return;
        int p = n-1, c = n-1;
        while(p >= 0)
        {
            if(p != n-1 && nums[p] < nums[p+1])
                break;
            p--;
        }
        if(p < 0)
        {
            std::reverse(nums.begin(), nums.end());
            return;
        }
        while(c > 0)
        {
            if(nums[c] > nums[p])
                break;
            c--;
        }
        int temp = nums[p];
        nums[p] = nums[c];
        nums[c] = temp;

        std::reverse(nums.begin()+p+1, nums.end());
        return;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,002评论 0 33
  • ​ 今天要分享的书叫做《学会学习》,主要内容为:概念法、模仿法以及限定法。 001概念法 如何对一个认识来进行概念...
    娜娜_51cf阅读 377评论 0 0
  • 你听, 窗外的蝉在低低的鸣叫, 可声音的来源是你不可企及的远方, 你想起了去年的夏天, 背上画板的你走上了义无反顾...
    亦琪阅读 265评论 2 1
  • 黑幕会掩去细节 但你喜欢啊 接上文 昨天写到 我饶有兴致的去附近的公园摘了几支腊梅。 然后 我又在夜里摆弄起它们....
    Chris的另一个世界阅读 624评论 0 1
  • 文字/从简从心 摄影/从简从心 器材/尼康D7000 此组组照片摄于2016年三月份,在色影无忌发过贴,石沉大海,...
    至简从心阅读 1,949评论 5 5

友情链接更多精彩内容