Problem : https://leetcode.com/problems/rotate-array/
A solution uses separate cache.
Time Complexity = O ( N )
Space Complexity = O ( N )
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
offset = len(nums) - (k % len(nums))
tmp = nums[offset:] + nums[:offset]
for i in range(len(nums)):
nums[i] = tmp[i]
Reverse 3 times solution:
Time Compelxity = O ( N )
Space Complexity = O ( 1 )
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(left, right):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
N = len(nums)
pivot = N - k % N
# reverse the left side of pivot
reverse(0, pivot-1)
# reverse the right side of pivot
reverse(pivot, N-1)
# reverse the entire array
reverse(0, N-1)
No comments:
Post a Comment