670. Maximum Swap
Problem description:
You are given an integer num
. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
1 | Input: num = 2736 |
Example 2:
1 | Input: num = 9973 |
Constraints:
0 <= num <= 108
Solution:
Use an array to note the last occurence of each digits(0~9)
Then traverse from left to right, for arr[i]
, if we find there’s a bigger digit and its locate after i
, then we do the swap and return it.
Note we could start from 9
to int(arr[i])
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: