Leetcode 670. Maximum Swap

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Swap

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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))

Reference

  1. https://leetcode.com/problems/maximum-swap/
如果有收获,可以请我喝杯咖啡!