zoukankan      html  css  js  c++  java
  • 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

     
     本题开始的时候题意没有读懂,看了别人的解释才看懂,大致思路是
    1.从右面往左面遍历,如果找到数组下一个的值小于(不包括等于)当前值(即本来是从右往左是递增序列,但是被打断的元素)提取出来
    2.再一次从右往左遍历,直到当前数组值大于提取出来的值后,交换这两个位置。
    3.将从右到左不断递增的数组区间反转。
    代码如下:
     1 public class Solution {
     2     public void nextPermutation(int[] nums) {
     3         int index = nums.length;
     4         for(int i=nums.length-1;i>=1;i--){
     5             if(nums[i-1]>=nums[i]) continue;
     6             index = i-1;
     7             break;
     8         }
     9         if(index!=nums.length){
    10             for(int i=nums.length-1;i>=index;i--){
    11             if(nums[i]<=nums[index]) continue;
    12             swap(nums,index,i);
    13             break;
    14             }
    15             reverse(nums,index+1,nums.length-1);
    16         }else{
    17             reverse(nums,0,nums.length-1);
    18         }
    19     }
    20     public void swap(int[] nums,int i,int j){
    21         int temp = nums[i];
    22         nums[i] = nums[j];
    23         nums[j] = temp;
    24     }
    25     public void reverse(int[] nums,int left,int right){
    26         while(left<right){
    27             swap(nums,left++,right--);
    28         }
    29     }
    30 }

    本题主要考查细心程度。

  • 相关阅读:
    Java & XML学习笔记
    爱情与婚姻
    压缩数据以节省空间和提高速度(网上摘取)
    网线的直连线与交叉线
    java虚拟机 堆内存设置
    如何在 JavaScript 中实现拖放
    这几天遇上个问题,在SQL SERVER存储过程中提示字符串格式不正确
    如何编程实现VB.NET数据集中的数据导出到EXCEL
    SQL SERVER的数据类型
    终于拥有了自己的BLOG了!庆祝一下!^_^
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6386087.html
Copyright © 2011-2022 走看看