leetcode - 31. Next Permutation - Medium

descrition

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

暴力解决,O(n!) 的时间复杂度求出数组的全排列,然后返回比当前排列大的序列中最小的。

方法 2

时间复杂度:O(n);空间复杂度:O(1)

这里有很好的解释

不失一般性,假设数组如图所示。我们从后往前遍历数组,比较相邻的两个数,直到出现前一个数小于后一个数时,循环停止。如图中 a[i-1] < a[i],循环的结果有以下两点说明:

  • 在 a[i,...n-1] 是非递增有序(递减有序)的数组,因为 for 循环提前结束的条件是 a[i-1] < a[i],如果没有提前结束则说明,a[i-1] > a[i]。在这样的情况下,我们需要找到 a[i,...,n-1] 中比 a[i-1] 大的数中最小的那个,假设为 a[j]。将 a[j] 和 a[i-1] 交换,由数组的性质可得 a[i,...,n-1] 依然保持非递增(递减)有序,这时我们只需要将 a[i,...,n-1] 反转,即可得到下一个最小的排列。
  • 如果循环没有提前结束,则说明每一次比较都是 a[i-1] > a[i],说明整个数组非递增(递减)有序。在这样的情况下直接将数组反转即可得到最小的排列。

具体实现的逻辑参看代码。

code


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.empty())
            return;

        int isplit = -1;
        for(int i=nums.size()-1; i>0; i--){
            if(nums[i-1] < nums[i]){
                isplit = i-1;
                break;
            }
        }

        // if isplit == -1, which indicate nums is in descending
        // otherwhise, [isplit+1, n-1] is descending

        if(isplit == -1){
            reverse(nums, 0, nums.size()-1);
        }else{
            // construct next permutation
            // find the smallest one from the numbers which larger than nums[isplit]
            int ismallest = nums.size()-1;
            while(ismallest>isplit && nums[ismallest] <= nums[isplit])
                ismallest--;

            // nums[ismallest] > nums[isplit] >= nums[ismallest+1, ... , n-1]
            // and  nums[isplit+1, ismallest-1] >= nums[ismallest] >= nums[ismallest+1,..,n-1]
            swap(nums[isplit], nums[ismallest]);

            // nums[isplit+1, ... , n-1] still in descending
            // so just reverse
            reverse(nums, isplit+1, nums.size()-1);
        }
    }

    void reverse(vector<int>& nums, int ileft, int iright){
        while(ileft < iright){
            swap(nums[ileft], nums[iright]);
            ileft++;
            iright--;
        }
    }
};

int main()
{
    return 0;
}

[array] leetcode - 31. Next Permutation - Medium的更多相关文章

  1. LeetCode - 31. Next Permutation

    31. Next Permutation Problem's Link ---------------------------------------------------------------- ...

  2. [array] leetcode - 48. Rotate Image - Medium

    leetcode - 48. Rotate Image - Medium descrition You are given an n x n 2D matrix representing an ima ...

  3. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  4. LeetCode 31. Next Permutation (下一个排列)

    Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...

  5. leetCode 31.Next Permutation (下一个字典序排序) 解题思路和方法

    Next Permutation  Implement next permutation, which rearranges numbers into the lexicographically ne ...

  6. Java [leetcode 31]Next Permutation

    题目描述: Implement next permutation, which rearranges numbers into the lexicographically next greater p ...

  7. leetcode 31. Next Permutation(字典序的下一个)

    描述: Implement next permutation, which rearranges numbers into the lexicographically next greater per ...

  8. [array] leetcode - 54. Spiral Matrix - Medium

    leetcode-54. Spiral Matrix - Medium descrition GGiven a matrix of m x n elements (m rows, n columns) ...

  9. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

随机推荐

  1. ASP.NET 5 Target framework dnx451 and dnxcore50

    中文不知如何定义标题,所以干脆就直接贴出关键字,在 ASP.NET 5 项目的 project.json 配置文件中,会有这样的定义: "frameworks": { " ...

  2. vue-validator(vue验证器)

    官方文档:http://vuejs.github.io/vue-validator/zh-cn/index.html github项目地址:https://github.com/vuejs/vue-v ...

  3. 【原】iOS学习之UIStoryboardSegue解析

    在 Storyboard 的可视化编程中,跳转界面就是按住 Ctrl 使用鼠标头一条连线就可以解决,相当的简单!本篇博客主要就是介绍这条连线,在iOS中,这条连线也是一个对象,也有其自己的初始化方法和 ...

  4. 三天学会HTML5 之第一天

    引言 HTML5 一直是非常热门的话题,因此此系列文章主要从一些基本功能开始讲起,逐步深入了解HTML5的新概念. 首先了解一些基本的术语和概念. SGML, HTML,XML三者之间的区别 Doc类 ...

  5. 9.22 JS脚本语言DOM

    通用:onclick 鼠标单击ondblclick 鼠标双击onmouseover 鼠标放上onmouseout 鼠标离开onmousemove 鼠标移动 表单:onchang 表单的值改变onblu ...

  6. [MVCSharp]开始使用MVC#

    Getting started with MVC# framework The source code of this example can be found under "Example ...

  7. sdut2169Sequence(dp)

    http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2169 感觉是有递归思想的 dp[j]表示从1到 ...

  8. context-param引发spring容器以及servlet容器的关联

    转自:http://blog.csdn.net/liaoxiaohua1981/article/details/6759206 格式定义: [html] view plaincopy <cont ...

  9. MIT算法导论——第五讲.Linear Time Sort

    本栏目(Algorithms)下MIT算法导论专题是个人对网易公开课MIT算法导论的学习心得与笔记.所有内容均来自MIT公开课Introduction to Algorithms中Charles E. ...

  10. CAS认证(1):流程详解

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...