Desctiprion
给定序列,寻找下一个比他大的permutation
Solution
思路:
- 从后找,到非上升序列时停止
- (i)/ (i+1)\ ,对于i, 从i+1往后寻找比他大的最小值,并交换(keep order)
- 最后reverse i+1往后的数组
class Solution:
def reverse(self,nums,start):
i = start
j = len(nums) - 1;
while i < j:
tmp = nums[i]
nums[i] = nums[j]
nums [j] = tmp
i+=1
j-=1
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
sub_max = -1
flag = 0
i=len(nums)-1
while i>0:
if nums[i-1]< nums[i]: # Not increase from backwards
break
i-=1
start = i-1
if i >0:
# Find the min greater number
j=i
while j<len(nums):
if nums[start] >= nums[j]:
break
j+=1
j-=1
# swap
tmp = nums[start]
nums[start] = nums[j]
nums [j] = tmp
self.reverse(nums,start+1)
网友评论