Leetcode 670. Maximum Swap
2021-02-03 本文已影响0人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Maximum Swap2. Solution
- Version 1
class Solution:
def maximumSwap(self, num):
s = list(str(num))
length = len(s)
if length < 2:
return num
for i in range(length - 1):
max_index = i
for j in range(i + 1, length):
if s[j] >= s[max_index] and s[i] != s[j]:
max_index = j
if max_index != i:
temp = s[i]
s[i] = s[max_index]
s[max_index] = temp
break
return int(''.join(s))
- Version 2
class Solution:
def maximumSwap(self, num):
s = list(str(num))
length = len(s)
if length < 2:
return num
pre = 0
post = 0
max_index = length - 1
for i in range(length - 1, -1, -1):
if s[i] > s[max_index]:
max_index = i
elif s[i] < s[max_index]:
pre = i
post = max_index
temp = s[pre]
s[pre] = s[post]
s[post] = temp
return int(''.join(s))