zoukankan      html  css  js  c++  java
  • leetcode[31]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,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
        int i=0,j=0,k=0;
        int n=num.size();
        if (n==0||n==1)return;
        if(n==2)
        {
           reverse(num.begin(),num.end());
           return;
        }
        int jj=0;
        for(;jj<num.size()-1;jj++)
        {
            if (num[jj]<num[jj+1])
            {
                break;
            }
        }
        if(jj==num.size()-1)
        {
            reverse(num.begin(),num.end());
            return;
        }
        for (j=num.size()-2;j>=0;j--)
        {
            if(num[j]<num[j+1])break;
        }
        i=j+1;
        for (k=num.size()-1;k>=0;k--)
        {
            if(num[i-1]<num[k])break;
        }
        j=k;
        int temp=num[i-1];
        num[i-1]=num[j];
        num[j]=temp;
        reverse(num.begin()+i,num.end());     
        }
    };
  • 相关阅读:
    KMP算法
    找出第二大的数
    webpack 3 优化
    CocoaPods安装
    自适应水平垂直居中
    找出两个数组中都有,并且重复次数最多的元素
    swift 笔记
    Promise 用es5的基础实现
    $.ajax仿axios封装
    js基础拖拽效果
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283610.html
Copyright © 2011-2022 走看看