[LeetCode][JavaScript]Next Permutation

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code

The replacement must be in-place, do not allocate extra memory.blog

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,1leetcode

https://leetcode.com/problems/next-permutation/

 

 


 

 

求出下一个排列。字符串

字符串的大小就是一位位去比较,下一个排列恰好比当前的排列大。get

最简单的状况是[1, 2, 3],只须要交换最后两位就获得了下一个序列。it

复杂的状况[1, 2, 4, 3],发现最后的子串[4, 3]已是最大了的,那么须要移动一个比2大一级的数3到前面,后面子串保持递增[2, 4],结果是[1, 3, 2, 4]。io

再好比[1, 4, 7, 5, 3, 2],结果是[1, 5, 2, 3, 4, 7]function

实现的时候,先判断是否是递减序列,若是是reverse所有,class

不然先交换一位,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 };
相关文章
相关标签/搜索