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 }

    本题主要考查细心程度。

  • 相关阅读:
    在Ubuntu11.10中安装OpenCV2.3.1的详细步骤
    基于二元语法模型的中文分词
    相似图片搜索的原理
    基于GPU的KMeans聚类算法
    Windows下Eclipse和PyDev搭建完美Python开发环境
    Ubuntu 11.10+win7双系统启动项管理及配置方法
    主题爬虫
    vue定义全局过滤器
    element elimage 放多张图片,显示大图
    element UI的form 禁止浏览器自动填充用户名或密码
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6386087.html
Copyright © 2011-2022 走看看