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());
        }
    };
  • 相关阅读:
    Leetcode Power of Two
    Leetcode Reverse Integer
    Leetcode Add Digits
    Leetcode Roman to Integer
    Python 函数的定义语法
    Python 函数的三种定义方式
    Python 函数的定义与调用
    Python 函数分类
    Python 为什么要使用函数
    Python 文件的二进制读写
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353437.html
Copyright © 2011-2022 走看看