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 }
  • 相关阅读:
    错误及异常处理-[PathTooLongException]指定的路径或文件名太长
    在线颜色转换器
    文件被锁定的原因
    EF6官方文档
    我关注的
    "此实现不是 Windows 平台 FIPS 验证的加密算法的一部分"解决办法
    Rsync Error set gid failed rsync error
    转载——EntiyFrameWork教程
    Word 出现“因为没有打开的文档,所以这一命令无效”的错误
    Winsock网络编程笔记:基于UDP的Client
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4231819.html
Copyright © 2011-2022 走看看