31. Next Permutation

Difficulty:
Related Topics:
Similar Questions:

Problem

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,31,3,2

3,2,11,2,3

1,1,51,5,1

Solution

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var nextPermutation = function(nums) {
  var len = nums.length;
  var i = len - 2;
  var j = len - 1;

  while (i >= 0 && nums[i] >= nums[i + 1]) i--;

  if (i >= 0) {
    while (j > i && nums[j] <= nums[i]) j--;
    swap(nums, i, j);
    reverse(nums, i + 1, len - 1);
  } else {
    reverse(nums, 0, len - 1);
  }
};

var swap = function (arr, from, to) {
  var tmp = arr[from];
  arr[from] = arr[to];
  arr[to] = tmp;
};

var reverse = function (arr, start, end) {
  while (start < end) {
    swap(arr, start, end);
    start++;
    end--;
  }
};

Explain:

  1. 从后往前找,直到 nums[i] < nums[i + 1]
  2. 找到 i 后,从后往前找,直到 nums[j] > nums[i],交换 nums[i]nums[j],然后把 i 后的倒置一下
  3. 没找到 i 的话,直接倒置一下

Complexity: