Re: [閒聊] 每日leetcode

作者: dont   2024-10-17 19:57:54
670. Maximum Swap
## 思路
先轉成str list
再從後面掃回來, 記錄當前最大值的idx
如果目前的值比最大值還小, 就更新swap的idx pair
## Code
```python
class Solution:
def maximumSwap(self, num: int) -> int:
arr = list(str(num))
n = len(arr)
max_idx = n-1
swap = None
for i in range(n-2, -1, -1):
if arr[i] > arr[max_idx]:
max_idx = i
elif arr[i] < arr[max_idx]:
swap = (i, max_idx)
if swap:
arr[swap[0]], arr[swap[1]] = arr[swap[1]], arr[swap[0]]
return int(''.join(arr))
```

Links booklink

Contact Us: admin [ a t ] ucptt.com