Skip to content

Commit cfd2f02

Browse files
committed
670
1 parent 42d7ae0 commit cfd2f02

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

670/Solution.java

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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+
}

670/main.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@
131131
- [581 Shortest Unsorted Continuous Subarray](./581)
132132
- [621 Task Scheduler](./621)
133133
- [628 Maximum Product of Three Numbers](./628)
134+
- [670 Maximum Swap](./670)
134135
- [675 Cut Off Trees for Golf Event](./675)
135136
- [681 Next Closest Time](./681)
136137
- [682 Baseball Game](./682)

0 commit comments

Comments
 (0)