31_Next Permutation
Example
Input: [1,2,3]
Output: [1,3,2]
Input: [3,2,1]
Output: [1,2,3]
Input: [1,1,5]
Output: [1,5,1]Solution
Last updated
Input: [1,2,3]
Output: [1,3,2]
Input: [3,2,1]
Output: [1,2,3]
Input: [1,1,5]
Output: [1,5,1]Last updated
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for k in range(len(nums)-1, 0, -1):
# find the first entry from the right that is larger than the previous entry
if nums[k-1] >= nums[k]:
continue
# find the smallest element on the right which is larger than nums[k-1]
l = len(nums) - 1
while nums[k-1] >= nums[l]:
l -= 1
# swap these two elements
nums[k-1], nums[l] = nums[l], nums[k-1]
# reverse the element on the right
nums[k:] = reversed(nums[k:])
return
nums.reverse()