[LeetCode/Python] 189. Rotate Array

도니·2025년 9월 12일

Interview-Prep

목록 보기
8/29
post-thumbnail

📌 문제

[LeetCode] 189. Rotate Array

📌 풀이

📌 코드 설계

📌 정답 코드

Solution 1: Slicing method

  • Time: O(n)
  • Space: O(n)
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)

        if n == 0: 
            return
        k %= n   # only need remainder rotations
        nums[:] = nums[-k:] + nums[:-k]

Solution 2: Reverse method

  • Time: O(n)
  • Space: O(1)
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)

        if n == 0:
            return
        
        k %= n
        if k == 0:
            return

        def rev(i, j):
            while i < j:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
                j -= 1

        rev(0, n - 1)    # reverse the whole array
        rev(0, k - 1)    # reverse first k elements
        rev(k, n - 1)    # reverse remaining n-k elements
profile
Where there's a will, there's a way

0개의 댓글