solution 1:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
# solution 1: create extra space and copy
# time O(N) space O(N)
if not nums or k<=0:
return
copy = []
size = len(nums)
for i in range(size):
copy.append(nums[i])
for j in range(size):
nums[(j+k)%size] = copy[j]
solution2
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
# main idea: get the last k , get the first size-k items, and concat them together
# time O(N) space O(1)
"""
3 swaps
"""
# naive solution
size = len(nums)
k = k% size
def swap(l,r):
while l<r:
nums[l],nums[r] = nums[r], nums[l]
l+= 1
r -= 1
swap(0,size-1)
swap(0,k-1)
swap(k,size-1)
??
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
cnt = 0
start = 0
cur = 0
num_target = nums[0]
tmp = 0
size = len(nums)
# main idea: keep rotating until having rotated n different elements
while cnt < size:
num_tar,nums[(cur+k) % size] = nums[(cur+k) % size], num_tar
cur = (cur+k) % size
cnt += 1
if (cur == start):
break