# 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


## 代码实现

### 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  墨云黑  阅读(44)  评论(0编辑  收藏