zoukankan      html  css  js  c++  java
  • LeetCode-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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            for(int i=num.size()-2;i>=0;i--){
                if(num[i]<num[i+1]){
                    //from i to end
                    //eg. 1243 
                    //first find 243 then find the next value bigger than 2,swap it with 2 and sort then we get 324
                    vector<int> one;
                    int ptr=i+1;
                    for(int j=i+2;j<num.size();j++){
                        if(num[j]>num[i]&&num[j]<num[ptr]){
                            ptr=j;
                        }
                    }
                    int temp=num[i];
                    num[i]=num[ptr];
                    num[ptr]=temp;
                    for(int j=i+1;j<num.size();j++)
                    one.push_back(num[j]);
                    sort(one.begin(),one.end());
                    for(int j=0;j<one.size();j++){
                        num[i+1+j]=one[j];
                    }
                    return;
                }
            }
            sort(num.begin(),num.end());
        }
    };
  • 相关阅读:
    [蓝桥] 基础练习 数列排序(java)
    关不掉之以假乱真
    关不掉.vbs
    1.3内置数据类型
    1.2成员变量+类变量+static关键字
    1.1变量+命名规则
    Java 大数任意进制转换
    打印十字图
    c语言求最大公约数和最小公倍数
    核桃的数量
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353437.html
Copyright © 2011-2022 走看看