LeetCode链接
使用额外的数组 时间复杂度O(N) 空间复杂度O(N)
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
new_nums = nums[:]
nums_len = len(nums)
for i in range(nums_len):
new_nums[(i + k) % nums_len] = nums[i]
nums[:] = new_nums[:]
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
nums[:] = nums[-k:] + nums[ :-k]
数组翻转 时间复杂度O(N) 空间复杂度O(1)
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
def reverse(self, nums: List[int], start, end):
while start < end:
nums[start] , nums[end] = nums[end], nums[start]
start += 1
end -= 1
|