方法一:将pop出的数首段插入到数组中,由于首段插入是O(n)复杂度,所以整个代码复杂度为O(k*n)
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.
"""
for i in range(k):
nums.insert(0,nums.pop())
2.运行结果:(从效果上来看效果并不好)
方法二、采用三步翻转法
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.
"""
n=len(nums)
k=k%n
i,j=0,n-k-1
while i<j:
nums[i],nums[j]=nums[j],nums[i]
i,j=i+1,j-1
i,j=n-k,n-1
while i<j:
nums[i],nums[j]=nums[j],nums[i]
i,j=i+1,j-1
i,j=0,n-1
while i<j:
nums[i],nums[j]=nums[j],nums[i]
i,j=i+1,j-1
2.运行结果(效果还可以)