ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 31. Next Permutation
    Leetcode 2021. 6. 16. 15:12

    31. Next Permutation

    Medium

    59131980Add to ListShare

    Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

    If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

    The replacement must be in place and use only constant extra memory.

     

    Example 1:

    Input: nums = [1,2,3] Output: [1,3,2]

    Example 2:

    Input: nums = [3,2,1] Output: [1,2,3]

    Example 3:

    Input: nums = [1,1,5] Output: [1,5,1]

    Example 4:

    Input: nums = [1] Output: [1]

     

    Constraints:

    • 1 <= nums.length <= 100
    • 0 <= nums[i] <= 100
    class Solution:
        def nextPermutation(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            i = len(nums) - 2
            flag = False
    
            while i>=0:
                if nums[i] < nums[i+1]:
                    flag = True
                    break
                i -= 1
    
            if not flag:
                nums.sort()
                return nums
                print(nums)
            else:
                j = len(nums)-1
                while nums[j] <=nums[i] and j > i:
                    j -= 1
    
                nums[i], nums[j] = nums[j], nums[i]
                nums[i+1:] = nums[i+1:][::-1]

    - python은 inplace swap이 가능한 점

    - 정렬 알고리즘 중 이러한 정렬 알고리즘도 있다는것..

     

    'Leetcode' 카테고리의 다른 글

    35. Search Insert Position  (0) 2024.04.13
    30. Substring with Concatenation of All Words  (0) 2021.06.21
    29. Divide Two Integers  (0) 2021.05.25
    28. Implement strStr()  (0) 2021.05.25
    27. Remove Element  (0) 2021.05.25
Designed by Tistory.