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

    题意

    给一个整型数组如num[] = 1, 3, 2,这个数组组成一个数组132,下一个比他大的是2,1,3。如果给定的数组存在这样的一个Next,把数组重新按照新的next排好序。如果不存在,比如3,2,1就不存在这样的,返回这个数组组成的最小整数1,2,3数组顺序也变为num[] = 1,2,3

    思路

    从最后开始遍历,如果出现num[i] > num[i - 1]说明存在这样的next,找出i后面的最小值和i - 1进行交换,在对i及i后面的数组进行降序排列。如果不存在这样的next,对数组进行升序排列。

     1 import java.util.Arrays;
     2 
     3 public class Solution {
     4     public void nextPermutation(int[] num) {
     5         if(num.length == 0 || num.length == 1)
     6             return;
     7         boolean found = false;
     8         int index = 0;
     9         int comparaValue = 0;
    10         for(int i = num.length - 1; i > 0; i--){        //找出出现降序的位置
    11             if(num[i] > num[i - 1]){                    //这里不能交换
    12                 index = i;
    13                 comparaValue = i - 1;
    14                 found = true;
    15                 break;
    16             }//if
    17         }//for
    18         if(found){        //有可能
    19             int min = index;
    20             for(int i = min; i < num.length; i++){
    21                 if(num[i] > num[comparaValue] && num[i] < num[min]){
    22                     min = i;
    23                 }//if                
    24             }//for
    25             int temp = num[min];
    26             num[min] = num[comparaValue];
    27             num[comparaValue] = temp;
    28             
    29             //对index后面的进行升序排列
    30             for(int i = index; i < num.length; i++){
    31                 min = i;
    32                 for(int j = i + 1; j < num.length; j++){
    33                     if(num[min] > num[j])
    34                         min = j;
    35                 }//for
    36                 if(min != i){
    37                     temp = num[min];
    38                     num[min] = num[i];
    39                     num[i] = temp;
    40                 }
    41             }
    42         }//if 
    43         else{
    44             Arrays.sort(num);
    45         }
    46     }
    47 }
  • 相关阅读:
    企业微信通讯录替换-JqueryWEUI Picker替换通讯录
    页面window.onload冲突
    企业微信调试工具
    企业微信:错误码:50001 redirect_url 一例问题解决办法
    企业微信通讯录替换-Echarts中使用部门名称
    紫光拼音输入法切换中英文
    企业微信服务商平台申请
    企业微信通讯录替换-根据员工姓名查找工号
    微信开发 40001 invalid credential
    请求验证过程检测到有潜在危险的客户端输入值,对请求的处理已经中止
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4231819.html
Copyright © 2011-2022 走看看