[LeetCode] 31. Next Permutation

A successive arrangement. Casual working is the meaning of the questions, examples,

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

If itself is a descending, such as [3, 2, 1] Returns [1, 2, 3]. Running a normal example of it, such as [1, 5, 8, 4 , 7, 6, 5 , 3, 1], its next permutations are [1, 5, 8, 5 , 1, 3, 4 , 6 , 7]. Because the input itself is a permutation, and is based on lexicographic order, it was found that the latter five figures 4 descending (7, 6, 5, 3, 1); his next arrangements are needed to find the minimum ratio of 4 a large number (5) and all the numbers into ascending 4 behind the reverse. With this idea, so the beginning of the array need to use a pointer i sweep from right to left, to find the number (4) is not the ascending order of the first, stop; and then the second pointer j second sweep from right to left , this time looking for more than the first 4 large numbers, will stop at position 5; 5 to 4 with the change of location;

[1, 5, 8, 4, 7, 6, 5, 3, 1] -> [1, 5, 8, 5, 7, 6, 4, 3, 1]

Finally, after inversion five numbers, so a to obtain the next permutation.

[1, 5, 8, 5, 7, 6, 4, 3, 1] -> [1, 5, 8, 5, 1, 3, 4, 6, 7]

Time O (n)

Space O (1)

 1 /**
 2  * @param {number[]} nums
 3  * @return {void} Do not return anything, modify nums in-place instead.
 4  */
 5 var nextPermutation = function (nums) {
 6     let i = nums.length - 2;
 7     while (i >= 0 && nums[i] >= nums[i + 1]) {
 8         i--;
 9     }
10     if (i >= 0) {
11         let j = nums.length - 1;
12         while (j >= 0 && nums[j] <= nums[i]) {
13             j--;
14         }
15         swap(nums, i, j);
16     }
17     reverse(nums, i + 1);
18 };
19 
20 var reverse = function (nums, start) {
21     let i = start;
22     let j = nums.length - 1;
23     while (i < j) {
24         swap(nums, i, j);
25         i++;
26         j--;
27     }
28 };
29 
30 var swap = function (nums, i, j) {
31     let temp = nums[i];
32     nums[i] = nums[j];
33     nums[j] = temp;
34 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12418303.html