코딩테스트/Python

[LeetCode] 189. Rotate Array

swwho 2023. 11. 28. 13:51
728x90
반응형

🔗 Problem Link

 

Rotate Array - LeetCode

Can you solve this real interview question? Rotate Array - Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.   Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 step

leetcode.com


❔Thinking

  • 주어진 배열 자체를 변환해야 하고, 다른 배열을 선언하지 말아야 한다.

💻Solution

def rotate(self, nums: List[int], k: int) -> None:
    k = k % len(nums)
    nums[:] = nums[-k:]+nums[:len(nums)-k]

 


🗝️keypoint

  1. array = [1,2,3]는 array가 [1,2,3]을 가르키게 하지만, array[:] = [1,2,3]은 array가 [1,2,3]이 된다.