리트코드 189번 문제
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 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
- Input: nums = [-1,-100,3,99], k = 2
- Output: [3,99,-1,-100]
- Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
- 1 <= nums.length <= 105
- -231 <= nums[i] <= 231 - 1
- 0 <= k <= 105
k의 범위가 0부터 10^5까지니까 0이 아닌 나머지값에 대해서만 이동하면 되고, 추가적으로 기존 리스트를 기억할 메모리를 확보해 O(n) 복잡도로 해결한다.
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
remainder = k % length
if remainder == 0:
return
temp = nums.copy()
for i in range(remainder):
nums[i] = temp[length - remainder + i]
for i in range(length - remainder):
nums[remainder + i] = temp[i]
'코딩테스트' 카테고리의 다른 글
Python ] leetCode 1861 - Rotating the Box (0) | 2024.06.02 |
---|---|
C++ ] leetCode 85 - Maximal Rectangle (0) | 2024.05.20 |
C++ ] leetCode 84 - Largest Rectangle in Histogram (0) | 2024.05.18 |
C++ ] leetCode 42 - Trapping Rain Water (0) | 2024.05.14 |
C++ ] leetCode 937 - Reorder Data in Log Files (0) | 2024.05.10 |