문제링크
https://leetcode.com/problems/rotate-array/
Rotate Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
코드
풀이1
1
2
3
4
5
6
7
8
|
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]
|
cs |
풀이2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
def reverse(nums, i, j):
while i<j:
nums[i],nums[j] = nums[j], nums[i]
i+=1
j-=1
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
reverse(nums, 0, n-1)
reverse(nums, 0, k-1)
reverse(nums, k, n-1)
|
cs |
POINT
풀이1:
리스트 슬라이싱을 사용해서 필요한 부분만큼 잘라 리스트 앞에 붙였다.
풀이2:
reverse를 사용한 방법이다.
총 3번 reverse를 하는데,
첫번째는 0~끝까지 뒤집고, 두번쨰는 0~k-1까지 , 세번째는 k~끝까지 뒤집는다.
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 167. Two Sum II - Input Array Is Sorted (0) | 2022.03.02 |
---|---|
[LeetCode] 283. Move Zeroes (0) | 2022.03.02 |
[LeetCode] 977. Squares of a Sorted Array (0) | 2022.03.01 |
[LeetCode] 35. Search Insert Position (0) | 2022.02.28 |
[LeetCode] 278. First Bad Version (2) | 2022.02.28 |