原题
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 and use only constant 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
解法1
参考【LeetCode】31. Next Permutation 解题报告(Python & C++)
先从右至左找到第一个下降的数字, 记下它的位置, 记为left, 然后再从右至左找到比它大的最小值, 由于右边部分是递增的, 那么找到的第一个较大数的位置记为right, 交换left和right的值, 然后从left往右的第一个数开始, 将nums[left+1: ]倒转即可. 由于我们需要直接在nums上修改, 那么我们就互换nums[left+1: ]两边的值即可.
代码
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = len(nums)-1
while i >= 1 and nums[i-1] >= nums[i]:
i -= 1
if i== 0:
nums.reverse()
return
left = i-1
right = len(nums)-1
while nums[right] <= nums[left]:
right -= 1
# swap two values
nums[left], nums[right] = nums[right], nums[left]
# reverse the second part
left, right = left+1, len(nums)-1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
解法2
同解法1
代码
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i = len(nums)-1
# find the first decreased num from right to left
while i-1 >= 0 and nums[i-1]>=nums[i]:
i -= 1
if i==0:
# deepcopy nums
nums.reverse()
return
else:
# find the first bigger num from right to left
j = len(nums)-1
while nums[j] <= nums[i-1]:
j -= 1
# swap two nums
nums[i-1], nums[j] = nums[j], nums[i-1]
# reverse nums[i:]
nums[i:] = nums[i:][::-1]