实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
解法一:双指针交换
这题主要是要搞明白懂数学上的排列。分为四个步骤:
- Find nums[i] which is the first num ahead of the descending tail
- Find nums[j] which is the first num greater than nums[i] in the descending tail
- Swap nums[i] and nums[j]
- In-place reverse nums[i+1:] to make it ascending
class Solution:def nextPermutation(self, nums: List[int]) -> None:# 1. find the first num before the descending taili = len(nums) - 2while i >= 0 and nums[i] >= nums[i + 1]:i -= 1# 2. find the first num greater than nums[i] in the descending tailif i >= 0:j = len(nums) - 1while j >= 0 and nums[i] >= nums[j]:j -= 1nums[i], nums[j] = nums[j], nums[i]# 3. in-place reverse nums[i+1:] to make it ascendingleft, right = i + 1, len(nums) - 1while left < right:nums[left], nums[right] = nums[right], nums[left]left += 1right -= 1
