File tree 2 files changed +42
-1
lines changed
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,122 LeetCode solutions in JavaScript
1
+ # 1,123 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
858
858
1049|[ Last Stone Weight II] ( ./solutions/1049-last-stone-weight-ii.js ) |Medium|
859
859
1051|[ Height Checker] ( ./solutions/1051-height-checker.js ) |Easy|
860
860
1052|[ Grumpy Bookstore Owner] ( ./solutions/1052-grumpy-bookstore-owner.js ) |Medium|
861
+ 1053|[ Previous Permutation With One Swap] ( ./solutions/1053-previous-permutation-with-one-swap.js ) |Medium|
861
862
1071|[ Greatest Common Divisor of Strings] ( ./solutions/1071-greatest-common-divisor-of-strings.js ) |Easy|
862
863
1072|[ Flip Columns For Maximum Number of Equal Rows] ( ./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js ) |Medium|
863
864
1073|[ Adding Two Negabinary Numbers] ( ./solutions/1073-adding-two-negabinary-numbers.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1053. Previous Permutation With One Swap
3
+ * https://leetcode.com/problems/previous-permutation-with-one-swap/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an array of positive integers arr (not necessarily distinct), return the lexicographically
7
+ * largest permutation that is smaller than arr, that can be made with exactly one swap. If it
8
+ * cannot be done, then return the same array.
9
+ *
10
+ * Note that a swap exchanges the positions of two numbers arr[i] and arr[j]
11
+ */
12
+
13
+ /**
14
+ * @param {number[] } arr
15
+ * @return {number[] }
16
+ */
17
+ var prevPermOpt1 = function ( arr ) {
18
+ const result = [ ...arr ] ;
19
+ let swapIndex = - 1 ;
20
+
21
+ for ( let i = arr . length - 2 ; i >= 0 ; i -- ) {
22
+ if ( arr [ i ] > arr [ i + 1 ] ) {
23
+ swapIndex = i ;
24
+ break ;
25
+ }
26
+ }
27
+
28
+ if ( swapIndex === - 1 ) return arr ;
29
+
30
+ let maxLessIndex = swapIndex + 1 ;
31
+ for ( let j = swapIndex + 2 ; j < arr . length ; j ++ ) {
32
+ if ( arr [ j ] < arr [ swapIndex ] && arr [ j ] > arr [ maxLessIndex ] ) {
33
+ maxLessIndex = j ;
34
+ }
35
+ }
36
+
37
+ [ result [ swapIndex ] , result [ maxLessIndex ] ] = [ result [ maxLessIndex ] , result [ swapIndex ] ] ;
38
+
39
+ return result ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments