일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 릿코드
- 코드업
- C#
- 파이썬기초
- 빅데이터
- codeup
- nlp
- 파이썬기초100제
- GenAI
- 파이썬알고리즘
- gcp
- GenerativeAI
- 리트코드
- 자연어처리
- LeetCode
- 생성형AI
- Microsoft
- Python3
- 구글퀵랩
- Blazor
- 코드업파이썬
- 데이터사이언스
- Python
- TwoPointer
- 파이썬
- Azure
- 클라우드
- 투포인터
- 머신러닝
- 알고리즘
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)