Link: https://leetcode.com/problems/next-permutation/
Content:
Analysis:
next permutation means 仅仅比这个数大的下一个数
如果是一个降序的数,比如9876,则如何排列都没有比之更大的数,此时将数列逆序排列,即 sorted it in ascending order
从上也可知,我们可以先从后向前看,直到找到破坏降序的数,将之与仅仅比它大的数调换
eg: 12641
643为降序,这三个数无论怎样排列都无法比643大,因此在2上做文章,调一个仅仅比它大的数,为4,此时为 14621,后面三个数621为最大排序,应调为126,此时即为仅仅比原数大的数。
final result: 14126
Method:
Algorithm:
- traverse i the whole array, from back to front, until one number nums[i]<nums[i+1], partition = i
- because of the last i digits is in descending order, the last one is the smallest, j traverse from back to front, until nums[j], greater than nums[partition]. swap nums[j] and nums[partition].
- from partition+1 to len(nums)-1 in ascending order.
Code:
def nextpermutation(nums):
if len(nums) <= 1:
return nums
partition = -1
for i in range(len(nums)-2, -1, -1):
if nums[i] < nums[i+1]:
partition = i
break
if partition == -1:
nums.reverse()
return nums
else:
for j in range(len(nums)-1, partition, -1):
if nums[j] > nums[partition]:
nums[j], nums[partition] = nums[partition], nums[j]
break
left = partition + 1
right = len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
Attention:
break 用法 until… 还有注意各个block之间的关系
Time complexity:
O(n)