File tree 2 files changed +32
-0
lines changed
2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change 502
502
664|[ Strange Printer] ( ./0664-strange-printer.js ) |Hard|
503
503
667|[ Beautiful Arrangement II] ( ./0667-beautiful-arrangement-ii.js ) |Medium|
504
504
668|[ Kth Smallest Number in Multiplication Table] ( ./0668-kth-smallest-number-in-multiplication-table.js ) |Hard|
505
+ 670|[ Maximum Swap] ( ./0670-maximum-swap.js ) |Medium|
505
506
680|[ Valid Palindrome II] ( ./0680-valid-palindrome-ii.js ) |Easy|
506
507
684|[ Redundant Connection] ( ./0684-redundant-connection.js ) |Medium|
507
508
686|[ Repeated String Match] ( ./0686-repeated-string-match.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 670. Maximum Swap
3
+ * https://leetcode.com/problems/maximum-swap/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are given an integer num. You can swap two digits at most once to get the maximum
7
+ * valued number.
8
+ *
9
+ * Return the maximum valued number you can get.
10
+ */
11
+
12
+ /**
13
+ * @param {number } num
14
+ * @return {number }
15
+ */
16
+ var maximumSwap = function ( num ) {
17
+ const digits = [ ...( num ) . toString ( ) ] ;
18
+ const last = new Array ( 10 ) . fill ( - 1 ) ;
19
+ digits . forEach ( ( d , i ) => last [ d ] = i ) ;
20
+
21
+ for ( let i = 0 ; i < digits . length ; i ++ ) {
22
+ for ( let d = 9 ; d > digits [ i ] ; d -- ) {
23
+ if ( last [ d ] > i ) {
24
+ [ digits [ i ] , digits [ last [ d ] ] ] = [ digits [ last [ d ] ] , digits [ i ] ] ;
25
+ return + digits . join ( '' ) ;
26
+ }
27
+ }
28
+ }
29
+
30
+ return num ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments