forked from zzxboy1/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext_Permutation.js
More file actions
38 lines (38 loc) · 845 Bytes
/
Copy pathNext_Permutation.js
File metadata and controls
38 lines (38 loc) · 845 Bytes
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
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
if (nums.length <= 1) {
return;
}
var len = nums.length,
i = len - 1;
while (i > 0) {
if (nums[i - 1] < nums[i]) {
break;
}
i--;
}
var j = len - 1,
temp;
if (i > 0) {
while (j > i - 1) {
if (nums[j] > nums[i - 1]) {
temp = nums[i - 1];
nums[i - 1] = nums[j];
nums[j] = temp;
break;
}
j--;
}
}
j = 0;
while (j + i < Math.ceil((i + len - 1) / 2)) {
temp = nums[len - 1 - j];
nums[len - 1 - j] = nums[j + i];
nums[j + i] = temp;
j++;
}
return;
};