难度: Easy
原题连接
首先,要知道一点,k
如果大于nums
的长度了,那么其实进行 k % len(nums)
次就行了
其次,要注意k 为0
的情况
思路 1
- 空间复杂度: O(k)
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
if k != 0:
tmp = nums[-k:]
for j in range(len(nums)-1, k-1, -1):
nums[j] = nums[j-k]
nums[:k] = tmp
思路 2
- 空间复杂度: O(1)
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
思路 3
- 空间复杂度: O(1)
还有最容易想到的方法:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 1
k %= len(nums)
while i <= k :
i += 1
a = nums.pop()
nums.insert(0, a)