Skip to content

Commit bd2215f

Browse files
committed
Add solution #31
1 parent 4605473 commit bd2215f

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
|#|Title|Difficulty|
88
|:---|:---|:---|
99
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
10+
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1011
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
1112
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
1213
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
@@ -76,4 +77,4 @@
7677

7778
[MIT License](https://opensource.org/licenses/MIT)
7879

79-
Copyright (c) 2019-2020 [Josh Crozier](https://joshcrozier.com)
80+
Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com)

solutions/0031-next-permutation.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 31. Next Permutation
3+
* https://leetcode.com/problems/next-permutation/
4+
* Difficulty: Medium
5+
*
6+
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
7+
*
8+
* If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
9+
*
10+
* The replacement must be in place and use only constant extra memory.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @return {void} Do not return anything, modify nums in-place instead.
16+
*/
17+
var nextPermutation = function(nums) {
18+
let i = nums.length - 2;
19+
20+
while (i >= 0 && nums[i + 1] <= nums[i]) {
21+
i--;
22+
}
23+
24+
if (i >= 0) {
25+
let cursor = nums.length - 1;
26+
while (nums[cursor] <= nums[i]) {
27+
cursor--;
28+
}
29+
swap(nums, i, cursor);
30+
}
31+
32+
reverse(nums, i + 1);
33+
};
34+
35+
function reverse(nums, start) {
36+
let i = start;
37+
let j = nums.length - 1;
38+
39+
while (i < j) {
40+
swap(nums, i, j);
41+
i++;
42+
j--;
43+
}
44+
}
45+
46+
function swap(nums, i, j) {
47+
const temp = nums[i];
48+
nums[i] = nums[j];
49+
nums[j] = temp;
50+
}

0 commit comments

Comments
 (0)