일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Blazor
- 슬라이딩윈도우
- 자연어처리
- stratascratch
- GenerativeAI
- 니트코드
- medium
- 파이썬알고리즘
- 구글퀵랩
- 릿코드
- 투포인터
- gcp
- Python
- nlp
- slidingwindow
- LeetCode
- two-pointer
- 리트코드
- 알고리즘
- codeup
- 생성형AI
- SQL
- Python3
- Microsoft
- 파이썬
- dfs
- sql코테
- GenAI
- 파이썬기초100제
- 코드업
Archives
- Today
- Total
Tech for good
[Leetcode/TwoPointer] 189. Rotate Array 본문
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k = k % n # In case k is larger than n
# Step 1: Reverse the entire array
nums.reverse()
# Step 2: Reverse the first k elements
nums[:k] = reversed(nums[:k])
# Step 3: Reverse the remaining n-k elements
nums[k:] = reversed(nums[k:])
Explanation
For nums = [1,2,3,4,5,6,7] and k = 3:
- Reverse entire array: [7,6,5,4,3,2,1]
- Reverse first k elements (k=3): [5,6,7,4,3,2,1]
- Reverse remaining part: [5,6,7,1,2,3,4]
✅ Time Complexity: O(n)
✅ Space Complexity: O(1) (modifies the array in-place)
- In case of (n = k), nums = output
- However, in case of k >= n, k = spare of (k % n)