Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
思路
只能交换一次,很容易想到是要把最大的数字和最高位交换。最大的数字如果有很多个,则找最低位的那一个。
而一位数字的范围也就是0-9。
粗略想法:遍历最低位到最高位,找9。找到9以后就跟最高位交换。如果没有9,就-1,找8、7、6...
考虑如下例子:
Input: 9128 Output: 9821
当我们找到9时,它本身就是最高位。所以要跳过。
而我们找到8时,也不是跟最高位交换,而是跟第二位交换。
所以我们需要另一个int来记录“当前最高位”,初始值为0。
时间复杂度为n
class Solution:
def maximumSwap(self, num: int) -> int:
numlist = [int(i) for i in str(num)]
digit = 9
start = 0
while digit > 0:
for i in range(len(numlist) - 1, start - 1, -1):
if numlist[i] == digit:
while int(numlist[start]) >= digit:
start += 1
if start >= len(numlist) - 1:
return num
if start >= i:
break
temp = numlist[start]
numlist[start] = numlist[i]
numlist[i] = temp
numlist = ''.join([str(i) for i in numlist])
return int(numlist)
digit -= 1
return num
Runtime: 32 ms, faster than 88.68% of Python3 online submissions for Maximum Swap.
Memory Usage: 13.2 MB, less than 29.07% of Python3 online submissions for Maximum Swap.