670. 最大交换

670. 最大交换

解法一: 一次遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func maximumSwap(num int) int {
numArr := toNumArr(num)
n := len(numArr)
maxIndex := n - 1
left := -1
right := -1
for i := n - 1; i >= 0; i-- {
if numArr[i] > numArr[maxIndex] {
maxIndex = i
} else if numArr[i] < numArr[maxIndex] {
left = i
right = maxIndex
}
}
if left != -1 {
numArr[left], numArr[right] = numArr[right], numArr[left]
return toNum(numArr)
}
return num
}

func toNumArr(num int) []int {
numArr := []int{}
for num != 0 {
numArr = append(numArr, num%10)
num /= 10
}
left, right := 0, len(numArr)-1
for left < right {
numArr[left], numArr[right] = numArr[right], numArr[left]
left++
right--
}
return numArr
}

func toNum(numArr []int) int {
ans := 0
for _, num := range numArr {
ans = ans*10 + num
}
return ans
}
作者

wuhunyu

发布于

2024-01-22

更新于

2024-01-22

许可协议