美文网首页
31. Next Permutation

31. Next Permutation

作者: Mree111 | 来源:发表于2019-10-19 04:50 被阅读0次

    Desctiprion

    给定序列,寻找下一个比他大的permutation

    Solution

    思路:

    1. 从后找,到非上升序列时停止
    2. (i)/ (i+1)\ ,对于i, 从i+1往后寻找比他大的最小值,并交换(keep order)
    3. 最后reverse i+1往后的数组
    class Solution:
        def reverse(self,nums,start):
            i = start
            j = len(nums) - 1;
            while i < j:
                tmp = nums[i] 
                nums[i] = nums[j]
                nums [j] = tmp
                i+=1
                j-=1
            
                
        def nextPermutation(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            sub_max = -1
            flag = 0
            i=len(nums)-1
            while i>0:
                if nums[i-1]< nums[i]:  # Not increase from backwards
                    break
                i-=1 
            start = i-1
            if i >0:
                # Find the min greater number
                j=i
                while j<len(nums):
                    if  nums[start] >= nums[j]:
                        break
                    j+=1
                j-=1
                # swap
                tmp = nums[start] 
                nums[start] = nums[j]
                nums [j] = tmp
            self.reverse(nums,start+1)
    

    相关文章

      网友评论

          本文标题:31. Next Permutation

          本文链接:https://www.haomeiwen.com/subject/kllgmctx.html