0031. Next Permutation (M)

Next Permutation (M)

题目

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

题意

按照字典序,输出当前数字序列的下一个排序。如果已经是递减数列,则返回递增数列。

思路

对于一个任意元素不相同的序列来说,正序排列是最小的排列方式,相应的逆序排列是最大的排列方式,以整数序列{1, 2, 3}为例,{1, 2, 3}是第一个排列,{3, 2, 1}则是最后一个排列。明确这一点才能展开下面的分析。

从序列末尾向前查找,直到第一次出现nums[i - 1] < nums[i],这说明第i及i之后的数为逆序排列,已达到该子序列的最大排列方式,需要更新该子序列前一位数字(即nums[i - 1]),这时只要从末尾查找,将第一个比nums[i - 1]大的数与nums[i - 1]交换,再将i及i之后的数字逆序,即可得到下一个排列。


代码实现

Java

class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while (i >= 1 && nums[i] <= nums[i - 1]) {
            i--;
        }
        if (i == 0) {
            reverse(nums, 0, nums.length - 1);
        } else {
            int j = nums.length - 1;
            while (nums[j] <= nums[i - 1]) {
                j--;
            }
            int temp = nums[i - 1];
            nums[i - 1] = nums[j];
            nums[j] = temp;
            reverse(nums, i, nums.length - 1);
        }
    }

    private void reverse(int[] nums, int i, int j) {
        while (i <= j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function (nums) {
  let p = nums.length - 1
  while (p > 0 && nums[p - 1] >= nums[p]) {
    p--
  }
  if (p === 0) {
    nums.reverse()
    return
  } else {
    let q = nums.length - 1
    while (nums[p - 1] >= nums[q]) {
      q--
    }
    [nums[p - 1], nums[q]] = [nums[q], nums[p - 1]]
    q = nums.length - 1
    while (p < q) {
      [nums[p++], nums[q--]] = [nums[q], nums[p]]
    }
  }
}
posted @ 2020-06-25 01:38  墨云黑  阅读(103)  评论(0编辑  收藏  举报