【LeetCode】31. Next Permutation

时间:2023-03-09 07:32:00
【LeetCode】31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

题意:用现有的数字排序,找出比现在数字大的最小的数,如果没有的话,重新排序为最小值

思路:从低位往高位遍历,如果相邻高位比现位置值大的话,break

 class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
flag = 0
l = len(nums)
for i in range(l-1,0,-1):
if nums[i-1]<nums[i]:
flag = 1
break
if 1 == flag:
tmp = nums[i:]
tmp.sort()
nums[i:]=tmp
for k in range(i,l):
if nums[k]>nums[i-1]:
tmp = nums[k]
nums[k] = nums[i-1]
nums[i-1] = tmp
break
else:
nums.reverse()