问题描述
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.
说实在话这题刚开始没有看明白意思,其实后来也没看懂,最后写出来的代码是根据solution
自己复现的。
这一题的要求就是,给你一个array
,你给出这些元素的下一个全排列。这里不知道全排列的排列规律就没法做。
例子
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
2019-06-08
看了solution
这题的解题思路如下:
代码如下:
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if len(nums)<3:
return nums.reverse()
def swap(list,left_side, right_side):
tmp = nums[right_side]
nums[right_side] = nums[left_side]
nums[left_side] = tmp
return nums
for i in range(len(nums)-1,-1,-1):
if nums[i-1]<nums[i]:
first_point = i-1 #找到逆序第一个不满足nums[i-1]>num[i]的点
for j in range(len(nums)-1,first_point,-1):
if nums[j]>nums[first_point]:
second_point = j #逆序找到first_point之后最后一个比它大的值
#print(nums[second_point])
swap(nums,first_point,second_point) #交换位置
nums[first_point+1:] = sorted(nums[first_point+1:]) #后续位置重排列
#print(nums)
break
break
S = Solution()
# nums = [1,2]
# nums = [1,5,8,4,7,6,5,3,1]
# nums = [3,2,1]
# nums = [1,3,2]
# nums = [1,2,3]
# nums = [1,1,5]
nums =[2,2,0,4,3,1]
S.nextPermutation(nums)
结果分析
第一次时间空间消耗排名如此靠前!
Runtime: 16 ms, faster than 99.85% of Python online submissions for Next Permutation.
Memory Usage: 11.6 MB, less than 98.17% of Python online submissions for Next Permutation.
注意事项
基本思路动态图已经很直观了,在实现的时候还是有好些地方出错,主要就是慢慢调试吧。我调试过程中几个要注意的点:
- 从后往前找第一个不满足不满足
nums[i-1]>num[i]
的指针时,只找逆序的第一个,在这个if
语句后加上break
for j in range(len(nums)-1,first_point,-1):
找到第一个不满足nums[i-1]>num[i]
得到first-point
指针后,在后面的元素中逆序遍历找到第一个大于nums[first_point]
的点,要注意的就是python中逆序遍历时·for … range()·的用法,其中第二个参数意味着从后往前遍历到还剩n+1
个元素停下。- 在某一次测试中有测试样例
nums =[2,2,0,4,3,1]
不通过,这里也需要加上break
- 元素只有两个时,上述代码无法解决
nums = [1,2]
这样的样例。