[LeetCode][JavaScript]Next Permutation
Next Permutation
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, do not allocate 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, 4, 3],发现最后的子串[4, 3]已经是最大了的,那么需要移动一个比2大一级的数3到前面,后面子串保持递增[2, 4],结果是[1, 3, 2, 4]。
再比如[1, 4, 7, 5, 3, 2],结果是[1, 5, 2, 3, 4, 7]
实现的时候,先判断是不是递减序列,如果是reverse全部,
否则先交换一位,reverse后面的子串。
1 /** 2 * @param {number[]} nums 3 * @return {void} Do not return anything, modify nums in-place instead. 4 */ 5 var nextPermutation = function(nums) { 6 for(var i = nums.length - 1; i > 0 && nums[i] <= nums[i - 1]; i--); 7 if(i === 0){ 8 reverse(0, nums.length - 1); 9 return; 10 } 11 for(var j = i + 1; j < nums.length && nums[i - 1] < nums[j]; j++); 12 swap(i - 1, j - 1); 13 reverse(i, nums.length - 1); 14 return; 15 16 function reverse(start, end){ 17 while(start < end){ 18 swap(start, end); 19 start++; 20 end--; 21 } 22 } 23 function swap(i, j){ 24 var tmp = nums[i]; 25 nums[i] = nums[j]; 26 nums[j] = tmp; 27 } 28 };