leetcode-python-day12-第31题

========坚持30天刷leetcode=====

题目链接:https://leetcode-cn.com/problems/next-permutation/

leetcode-python-day12-第31题_第1张图片

结果:

leetcode-python-day12-第31题_第2张图片

分析:

思路是:

1)从后往前找不符合降序(大->小,可以相等)的第一个元素a,

2)然后从a的下一个元素开始往后找,找到最后一个大于a的元素b,

3)交换a,b的位置,

4)再将原先a位置后的所有元素,进行升序排序

5)特殊情况①:数组全为降序,逆转数组;

      特殊情况②:找到a后,a比数组最后一个元素c小,则交换a,c。不进行遍历寻找b

 

class Solution:
    def nextPermutation(self, nums):
        """
        Do not return anything, modify nums in-place instead.
        """
        llen=len(nums)
        if llen<2:
            return
        i=llen-1
        while i>0 and nums[i]<=nums[i-1]:
                i-=1
        if i==0:                  # ①
            nums.reverse()
        else:
            if nums[llen-1]>nums[i-1]:     # ②
                j=llen
            else:
                j=i
                while j

 

你可能感兴趣的:(leetcode)