forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31-nextPermutation.js
50 lines (45 loc) · 1.2 KB
/
31-nextPermutation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* search from right to left, find the first number smaller than it's next. (nums[i] < nums[i+1])
* let's say the index is p;
* have a second scan from right to left, find the first number bigger than nums[p], say the index is q,
* swap element at p and q, then reverse all elements from p+1 to the last element of nums.
*
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
if (!nums || nums.length === 1) return;
var p = nums.length - 1;
var q = nums.length - 1;
for (var i = p - 1; i >= 0; i--) {
if (nums[i + 1] > nums[i]) {
p = i;
break;
}
p--;
}
for (var i = q; i > p; i--) {
if (nums[i] > nums[p]) {
var tmp = nums[p];
nums[p] = nums[i];
nums[i] = tmp;
break;
}
q--;
}
if (p === 0 && q === 0) {
reverse(nums, p);
return;
}
reverse(nums, p + 1);
};
var reverse = function(nums, i) {
var j = nums.length - 1;
while (i < j) {
var tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
};