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,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,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:
- 从后往前找,直到
nums[i] < nums[i + 1]
- 找到
i
后,从后往前找,直到nums[j] > nums[i]
,交换nums[i]
、nums[j]
,然后把i
后的倒置一下 - 没找到
i
的话,直接倒置一下
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).