题目描述
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
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的序列,如果当前序列字典序最大,则变为字典序最小的序列。
当序列很长时,穷举其字典序及其耗时,因此采用其他方法
We need to find the first pair of two successive numbers a[i]a[i] and a[i-1]a[i−1], from the right, which satisfy a[i] > a[i-1]. Now, no rearrangements to the right of a[i-1] can create a larger permutation since that subarray consists of numbers in descending order. Thus, we need to rearrange the numbers to the right of a[i-1] including itself.
Now, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number a[i-1] with the number which is just larger than itself among the numbers lying to its right section, say a[j].
代码
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
i = len(nums) -2
while i>=0 and nums[i+1] <= nums[i]:
i -= 1
if i>= 0 :
j = len(nums) - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
self.swap(nums,i,j)
self.reverse(nums,i + 1)
def swap(self,nums,i,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def reverse(self,nums,start):
i = start
j = len(nums) -1
while i < j:
self.swap(nums,i,j)
i += 1
j -= 1
#############################################################################
Runtime: 40 ms, faster than 76.17% of Python3 online submissions for Next Permutation.
Memory Usage: 13.9 MB, less than 41.07% of Python3 online submissions for Next Permutation.