[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 };
相關文章
相關標籤/搜索