File tree Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change 7
7
| #| Title| Difficulty|
8
8
| :---| :---| :---|
9
9
4|[ Median of Two Sorted Arrays] ( ./0004-median-of-two-sorted-arrays.js ) |Hard|
10
+ 31|[ Next Permutation] ( ./0031-next-permutation.js ) |Medium|
10
11
36|[ Valid Sudoku] ( ./0036-valid-sudoku.js ) |Medium|
11
12
43|[ Multiply Strings] ( ./0043-multiply-strings.js ) |Medium|
12
13
58|[ Length of Last Word] ( ./0058-length-of-last-word.js ) |Easy|
76
77
77
78
[ MIT License] ( https://opensource.org/licenses/MIT )
78
79
79
- Copyright (c) 2019-2020 [ Josh Crozier] ( https://joshcrozier.com )
80
+ Copyright (c) 2019-2021 [ Josh Crozier] ( https://joshcrozier.com )
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments