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());
        }
    };
  • 相关阅读:
    认识v$fixed_view_definition
    V$、GV$、X$、V_$、GV_$之间的关系
    ORACLE OEM
    ORACLE表空间
    linux
    系统数据库备份恢复
    linux -- #!/bin/bash
    linux -- ubuntu 脚本开机自启动
    linux -- chown修改文件拥有者和所在组
    php -- php控制linux关机、重启、注销
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353437.html
Copyright © 2011-2022 走看看