LeetCode 31. Next Permutation

题目: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

最终被接受的代码如下:

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        len_num=len(nums)
        if len_num>=2:
            blag=0
            for j in range(len_num-2,-1,-1):
                for i in range(len_num-1,j,-1):               
                    if nums[i]>nums[j]:
                        blag=1
                        nums[i],nums[j]=nums[j],nums[i]
                        tmp=nums[j+1:]
                        tmp.sort()
                        nums[j+1:]=tmp
                        break
                if blag==1:
                    break
            else:
                nums.reverse()

注意一下几点:

1.在python3中,虽然对列表进行切片后的结果仍为列表,但好像无法调用List类型对应的内置方法。

>>> a
[1, 2, 3, 4, 5]
>>> a[1:].reverse()
>>> a
[1, 2, 3, 4, 5]
>>> 

所以这里定义了一个中间变量tmp,辅助更改列表。(至于为什么会出现这种情况,原因不明)

2.这个题目实际是寻找一个由列表中的与元素组成的数字中所有比现有数字大的最小数字。所以这里要注意两层for循环中,i和j谁做外循环,谁做内循环。刚开始我就是没有注意到这个问题,所以提交之后一直报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值