zoukankan      html  css  js  c++  java
  • [leetcode]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 and use only constant 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

    思路:

    给定一个排列,按照字典序把下一个排列找出来。

    Solution1: 

    code:

     1 /*
     2 Time: O(n).  We travese the given array
     3 Space: O(1). We only used constant extra space. 
     4 */
     5 
     6 class Solution {
     7        public void nextPermutation(int[] nums) {
     8         // corner case
     9         if (nums == null || nums.length == 0) return;
    10 
    11         int replace = nums.length - 2; //为何初始化为这个?因为下面要replace 和replace +1 比较
    12         while (replace >= 0) {
    13             if (nums[replace] < nums[replace + 1]) break;//从右往左扫
    14             replace--;
    15         }
    16         if (replace < 0) {//说明数组总没有出现nums[replace]<nums[replace+1], 则数组为 654321 这种排序
    17             Arrays.sort(nums); //返回题干说述的升序排列
    18             return;
    19         }
    20         int lgrIdx = replace + 1;
    21         //从nums[replace]往后,开始找剩下数字中,大于且最接近的nums[replace]的值
    22         while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) {
    23             lgrIdx++;
    24         }
    25         int temp = nums[replace];
    26         nums[replace] = nums[lgrIdx - 1];
    27         nums[lgrIdx - 1] = temp;
    28         Arrays.sort(nums, replace + 1, nums.length);
    29     }
    30 }
  • 相关阅读:
    2
    1
    Hadoop集群常见报错汇总
    Kerberos常见报错汇总
    Python软件包管理工具pip实战篇
    Python软件包及环境管理器conda实战篇
    Python的Virtualenv与Venv环境管理器
    Python的编辑工具-Jupyter notebook实战案例
    文档工具GitBook使用指南
    20200912
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9808264.html
Copyright © 2011-2022 走看看