LeetCode31: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


LeetCode:链接

这道题的目的就是让找到一个比当前数大的数,但是在众多大数中找到的这个数是最小的。我们要尽量用最少的比较得到最小的更大值。所以一定要从后往前遍历!!!

1. 由最低位(下表为nums.length-2)开始,由低往高遍历,找到可以进行替换的最小位。
2. 确定最小位之后,再从最低位开始调整,如果存在一个最低位比当前可以替换位的数值大,就进行交换。
3. 再将替换位之后的数字进行升序调整,此时得到的是最小的更大值。 

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) - 2
        # 由于下一个数比上一个数大,因此需要从后往前扫描,找到递增的位置设为元素i
        while i >= 0:
            if nums[i] < nums[i+1]:
                break
            i -= 1
        # 找不到,则将全部元素递增排序
        if i == -1:
            nums.sort()
        j = len(nums) - 1
        while j > i:
            if nums[j] > nums[i]:
                '''接下来,我们需要找到一个最大的下标j使得a[i]<a[j],交换a[i]和a[j]
                就是说递减序列中比a[i]大的最小的元素, 这样和位置i的进行交换,位置i之后的就又有全排列了
                '''
                nums[j], nums[i] = nums[i], nums[j]
                 # 最后对i+1之后的逆置即可,这样就变成了升序。
                nums[i+1:] = nums[i+1:][::-1]
                # 一旦找到直接退出循环
                break
            j -= 1

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值