下一个排列

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

解答:

  

/**
   * [1,2,3] 的字典序是[1,2,3];[1,3,2];[2,1,3];[2,3,1];[3,1,2];[3,2,1];这样的
   * @param nums
   */
  public static void nextPermutation(int[] nums) {
    /*当数组为null或元素小于1时直接返回*/
    if (nums == null || nums.length < 2) {
      return;
    }
    int length = nums.length;
    int c = length - 2;
    /*找出前一个元素比后一个元素小的下标*/
    while (c >= 0 && nums[c] >= nums[c + 1]) {
      c--;
    }
    /*当存在前一个元素比后一个元素小的下标*/
    if (c >= 0) {
      int in = length - 1;
      /*从数组末尾找到第一个比c大的元素下标*/
      while (in >= 0 && nums[in] <= nums[c]) {
        in--;
      }
      /*暂存c下标对应的值*/
      int tmp = nums[c];
      /*c下标赋值in对应的值*/
      nums[c] = nums[in];
      /*in下标赋值暂存c对应的值*/
      nums[in] = tmp;
    }
    /*从c+1开始,数组末尾截止,把元素翻转*/
    int start = c + 1;
    int end = length - 1;
    while (start < end) {
      int tmp = nums[start];
      nums[start] = nums[end];
      nums[end] = tmp;
      start++;
      end--;
    }
  }
View Code

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-permutation

原文地址:https://www.cnblogs.com/wuyouwei/p/11896739.html