[leetcode] 31. Next Permutation @ python

原题

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

解法1

参考【LeetCode】31. Next Permutation 解题报告(Python & C++)
先从右至左找到第一个下降的数字, 记下它的位置, 记为left, 然后再从右至左找到比它大的最小值, 由于右边部分是递增的, 那么找到的第一个较大数的位置记为right, 交换left和right的值, 然后从left往右的第一个数开始, 将nums[left+1: ]倒转即可. 由于我们需要直接在nums上修改, 那么我们就互换nums[left+1: ]两边的值即可.

代码

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        i = len(nums)-1
        while i >= 1 and nums[i-1] >= nums[i]:
            i -= 1
        if i== 0:
            nums.reverse()
            return
        left = i-1
        right = len(nums)-1
        while nums[right] <= nums[left]:
            right -= 1
        # swap two values
        nums[left], nums[right] = nums[right], nums[left]
        # reverse the second part
        left, right = left+1, len(nums)-1
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

解法2

同解法1

代码

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        i = len(nums)-1
        # find the first decreased num from right to left
        while i-1 >= 0 and nums[i-1]>=nums[i]:
            i -= 1
        if i==0:
            # deepcopy nums
            nums.reverse()
            return
        else:
            # find the first bigger num from right to left
            j = len(nums)-1
            while nums[j] <= nums[i-1]:
                j -= 1
            # swap two nums
            nums[i-1], nums[j] = nums[j], nums[i-1]
            # reverse nums[i:]
            nums[i:] = nums[i:][::-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值