LeetCode 31. Next Permutation (Python3)

题目描述

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). The replacement must be in place and use only constant extra memory.

解题思路

这道题应该属于一道规律技巧题,难度在于寻找规律. 我认为这道题的规律是: 变尾不变前,看代码:

代码

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if len(nums) == 1:
            return nums
        
        if nums[len(nums) - 1] > nums[len(nums) - 2]:
            temp = nums[len(nums) - 1]
            nums[len(nums) - 1] = nums[len(nums) - 2]
            nums[len(nums) - 2] = temp
            return nums
        
        cur = nums[len(nums) - 1]
        flag = 0
        for i in range(len(nums) - 2, -1, -1):
            if nums[i] < cur:
                flag = 1
                break
            else:
                cur = nums[i]
        if flag:
            for j in range(i + 1, len(nums)):
                if nums[j] > nums[i]:
                    if j == len(nums) - 1 or nums[j + 1] <= nums[i]:
                        temp = nums[i]
                        nums[i] = nums[j]
                        nums[j] = temp
          
            for j in range(i + 1, (len(nums) + i + 1) // 2):
                
                temp = nums[j]
                
                nums[j] = nums[len(nums) + i - j]
                nums[len(nums) + i - j] = temp
        
        else:
            for j in range(len(nums) // 2):
                temp = nums[j]
                nums[j] = nums[len(nums) - j - 1]
                nums[len(nums) - j - 1] = temp
                
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值