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: