File tree 3 files changed +47
-0
lines changed
3 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int maximumSwap (int num ) {
3
+ String n = Integer .toString (num );
4
+ String ans = n ;
5
+ for (int i = 0 ; i < n .length (); i ++) {
6
+ // StringBuilder sb = new StringBuilder(n);
7
+ for (int j = i + 1 ; j < n .length (); j ++) {
8
+ StringBuilder sb = new StringBuilder (n );
9
+ sb .replace (i , i + 1 , n .substring (j , j + 1 ));
10
+ sb .replace (j , j + 1 , n .substring (i , i + 1 ));
11
+ ans = max (sb .toString (), ans );
12
+ }
13
+ }
14
+ return Integer .parseInt (ans );
15
+ }
16
+
17
+ private String max (String a , String b ) {
18
+ return a .compareTo (b ) > 0 ? a : b ;
19
+ }
20
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } num
3
+ * @return {number }
4
+ */
5
+ var maximumSwap = function ( num ) {
6
+ const arr = ( num + '' ) . split ( '' ) . map ( x => + x )
7
+ const buckets = new Array ( 10 )
8
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
9
+ buckets [ arr [ i ] ] = i
10
+ }
11
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
12
+ for ( let j = 9 ; j > arr [ i ] ; j -- ) {
13
+ if ( buckets [ j ] > i ) {
14
+ ; [ arr [ i ] , arr [ buckets [ j ] ] ] = [ arr [ buckets [ j ] ] , arr [ i ] ]
15
+ return + arr . join ( '' )
16
+ }
17
+ }
18
+ }
19
+ return num
20
+ } ;
21
+
22
+ if ( process . env . LZS ) {
23
+ console . log ( maximumSwap ( 1234 ) )
24
+ console . log ( maximumSwap ( 9927 ) )
25
+ console . log ( maximumSwap ( 9987 ) )
26
+ }
Original file line number Diff line number Diff line change 131
131
- [ 581 Shortest Unsorted Continuous Subarray] ( ./581 )
132
132
- [ 621 Task Scheduler] ( ./621 )
133
133
- [ 628 Maximum Product of Three Numbers] ( ./628 )
134
+ - [ 670 Maximum Swap] ( ./670 )
134
135
- [ 675 Cut Off Trees for Golf Event] ( ./675 )
135
136
- [ 681 Next Closest Time] ( ./681 )
136
137
- [ 682 Baseball Game] ( ./682 )
You can’t perform that action at this time.
0 commit comments