Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f54c04b

Browse files
0031 next-permutation
1 parent 125bdff commit f54c04b

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
var swap = function (nums, i, j) {
2+
[nums[i], nums[j]] = [nums[j], nums[i]]
3+
}
4+
5+
/**
6+
* @param {number[]} nums
7+
* @return {void} Do not return anything, modify nums in-place instead.
8+
*/
9+
var nextPermutation = function (nums) {
10+
let i, n = nums.length;
11+
for (i = n - 1; i > 0; i--)
12+
if (nums[i] > nums[i - 1])
13+
break;
14+
15+
if (i == 0) {
16+
nums.reverse();
17+
// console.log(nums);
18+
return;
19+
}
20+
21+
let min = i, x = nums[i - 1];
22+
for (let j = i + 1; j < n; j++) {
23+
if (nums[j] > x && nums[j] < nums[min])
24+
min = j;
25+
}
26+
swap(nums, i - 1, min);
27+
28+
nums.slice(i, n).sort((a, b) => b - a).concat(nums.slice(0, i));
29+
console.log(nums);
30+
};
31+
32+
nextPermutation([1,3,2])
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const nextPermutation = nums => {
2+
const n = nums.length;
3+
for (let i = n - 2; i >= 0; i--) {
4+
if (nums[i] < nums[i + 1]) {
5+
for (let j = n - 1; j > i; j--) {
6+
if (nums[j] > nums[i]) {
7+
swap(nums, i, j);
8+
reverse(nums, i + 1, n - 1);
9+
return;
10+
}
11+
}
12+
}
13+
}
14+
nums.reverse();
15+
};
16+
17+
const swap = (nums, i, j) => ([nums[i], nums[j]] = [nums[j], nums[i]]);
18+
19+
const reverse = (nums, start, end) => {
20+
while (start < end) {
21+
swap(nums, start++, end--);
22+
}
23+
};
24+
25+
nextPermutation([1,3,2])
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Next Permutation
2+
3+
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
4+
5+
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
6+
7+
The replacement must be in-place and use only constant extra memory.
8+
9+
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
10+
11+
1,2,3 → 1,3,2
12+
13+
3,2,1 → 1,2,3
14+
15+
1,1,5 → 1,5,1
16+
17+
## More info
18+
19+
<https://leetcode.com/problems/next-permutation/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /