iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 41

[Day 41] Next Permutation (Medium)

  • 分享至 

  • xImage
  •  

31. Next Permutation

Solution 1: Two Pointer

class Solution:
    """
    Do not return anything, modify nums in-place instead.
    """
    def nextPermutation(self, nums: List[int]) -> None:
        idxOf1stNonIncreNum, idxOfSwapTgt = 0, 0
        
        n = len(nums)
        for idxI in range(n-2, -1, -1):
            if nums[idxI+1] >= nums[idxI]:
                idxOf1stNonIncreNum = idxI
                 
                for idxJ in range(n-1, idxOf1stNonIncreNum-1, -1):
                     if nums[idxJ] > nums[idxOf1stNonIncreNum]:
                        idxOfSwapTgt = idxJ
                        break
                
                # The idxOfSwapTgt is on the right of idxOf1stNonIncreNum
                if  idxOf1stNonIncreNum < idxOfSwapTgt:
                    nums[idxOf1stNonIncreNum], nums[idxOfSwapTgt] = nums[idxOfSwapTgt], nums[idxOf1stNonIncreNum]
                    nums[idxOf1stNonIncreNum + 1: ] = sorted(nums[idxOf1stNonIncreNum + 1: ])
                    return nums
        nums.sort()
        return nums

Time Complexity: O(N^2)
Space Complexity: O(1)

Reference

https://www.cnblogs.com/grandyang/p/4428207.html
https://medium.com/@ChYuan/leetcode-no-31-132-pattern-%E5%BF%83%E5%BE%97-medium-e02ecf53817f


上一篇
[Day 40] Subsets (Medium)
下一篇
[Day 42] Unique Binary Search Trees (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言