LintCode Q52 Next Permutation in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2017年1月14日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
# @param num : a list of integer
# @return : a list of integer
def nextPermutation(self, num):
# write your code here
if len(num) < 2:
return num
# find parition index where violets ascending order from right to left
parition_index = len(num) - 1
for i in xrange(len(num)-2, -1, -1):
if num[i] < num[i+1]:
parition_index = i
break
if parition_index == len(num) - 1:
return num[::-1]
# find change index where the first digit bigger than parition digit
change_index = len(num)
for i in xrange(len(num) - 1, -1, -1):
if num[i] > num[parition_index]:
change_index = i
break
# exchange the 2 digits
num[parition_index], num[change_index] = num[change_index], num[parition_index]
# reorder digits to the right of parition index
num[parition_index + 1:] = num[:parition_index:-1]
return num
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。