zoukankan      html  css  js  c++  java
  • Next Permutation:leetcode

    Question:

    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,2,3,4那么下一个为1,2,4,3,输入4,3,2,1下一个为1,2,3,4

    算法步骤:① 找到这样的最大下标k,使num[k]<num[k+1];

         ② 找到这样的最大下标j,使num[k]<num[j],如果k==j,那么num数组就是从大到小排列,输出数组的反序就可以,算法终止;

         ③ 交换num[k]和num[j];

         ④ 从第k+1个数往后的数要反序;

    Java代码

     1 public class Solution {
     2     public void nextPermutation(int[] num) {
     3         int k=0;//找到num[i]<num[i+1]的最大i
     4         for(int i=1;i<num.length;i++){
     5             if(num[i-1]<num[i]){
     6                 k=i-1;
     7             }
     8         }
     9  
    10         int j=k;//找到i之后,num[i]>num[k]的最大i
    11         for(int i=k;i<num.length;i++){
    12             if(num[k]<num[i]){
    13                 j=i;
    14             }
    15         }
    16         //交换num[k]和num[j]
    17         if(j==k){
    18             reverse(num, 0, num.length);//如果数组从大到小排列
    19             return ;
    20         }
    21         num[j]=num[k]+num[j];
    22         num[k]=num[j]-num[k];
    23         num[j]=num[j]-num[k];
    24         int length=num.length;
    25         reverse(num, k+1, length);
    26         
    27     }
    28     void reverse(int []array,int a,int b){
    29         
    30         for(int i=a;i<b;i++){
    31             int temp=array[i];
    32             array[i]=array[b-1];
    33             array[b-1]=temp;
    34             b--;
    35         }
    36     }
    37 }

     

     

  • 相关阅读:
    基于索引的MySQL优化
    SQL优化:
    in的对象选择(子查询还是List集合),in 的优化,in与exists
    嵌套查询及其作用域:
    group by实现原理及其作用
    批量打回未报bug修复
    解析Job,bpmn文件的小项目总结
    用户短时间内多次提交与保存带来的问题
    嵌套连接
    多范围读取优化
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/NextPermutation.html
Copyright © 2011-2022 走看看