Skip to content

Commit 0b20528

Browse files
authored
Merge pull request #983 from 0xff-dev/670
Add solution and test-cases for problem 670
2 parents b601702 + d91ccba commit 0b20528

File tree

3 files changed

+44
-23
lines changed

3 files changed

+44
-23
lines changed

leetcode/601-700/0670.Maximum-Swap/README.md

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,25 @@
11
# [670.Maximum Swap][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
You are given an integer `num`. You can swap two digits at most once to get the maximum valued number.
5+
6+
Return the maximum valued number you can get.
77

88
**Example 1:**
99

1010
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
11+
Input: num = 2736
12+
Output: 7236
13+
Explanation: Swap the number 2 and the number 7.
1314
```
1415

15-
## 题意
16-
> ...
17-
18-
## 题解
16+
**Example 2:**
1917

20-
### 思路1
21-
> ...
22-
Maximum Swap
23-
```go
2418
```
25-
19+
Input: num = 9973
20+
Output: 9973
21+
Explanation: No swap.
22+
```
2623

2724
## 结语
2825

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(num int) int {
4+
digits := make([]uint8, 0)
5+
for num > 0 {
6+
mod := num % 10
7+
digits = append(digits, uint8(mod))
8+
num /= 10
9+
}
10+
index := len(digits) - 1
11+
for ; index > 0; index-- {
12+
targetIndex := index
13+
for pre := index - 1; pre >= 0; pre-- {
14+
if digits[pre] >= digits[targetIndex] {
15+
targetIndex = pre
16+
}
17+
}
18+
if targetIndex != index && digits[targetIndex] != digits[index] {
19+
digits[targetIndex], digits[index] = digits[index], digits[targetIndex]
20+
break
21+
}
22+
}
23+
ans := 0
24+
for i := len(digits) - 1; i >= 0; i-- {
25+
ans = ans*10 + int(digits[i])
26+
}
27+
return ans
528
}

leetcode/601-700/0670.Maximum-Swap/Solution_test.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", 2736, 7236},
17+
{"TestCase2", 9973, 9973},
18+
{"TestCase3", 1993, 9913},
19+
{"TestCase4", 98368, 98863},
1920
}
2021

2122
// 开始测试
@@ -30,10 +31,10 @@ func TestSolution(t *testing.T) {
3031
}
3132
}
3233

33-
// 压力测试
34+
// 压力测试
3435
func BenchmarkSolution(b *testing.B) {
3536
}
3637

37-
// 使用案列
38+
// 使用案列
3839
func ExampleSolution() {
3940
}

0 commit comments

Comments
 (0)