题目:给一个数组,给定一个k,数组k steps向后移动,你知道的就是这样:
思路:
1、暴力倾向的我们总是不同意的你知道吧
然后是参考答案给出来的:
2、利用额外的数组进行辅助计算:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
a_list = list(nums)
i_k = i = 0
length = len(nums)
while i_k < length:
a_list[(i_k+k)%length] = nums[i_k]
i_k += 1
while i < length:
nums[i] = a_list[i]
i += 1
3、reverse:
class Solution(object):
def rotate(self, nums, k):
k %= len(nums)
self.reverse(0, len(nums)-1, nums)
self.reverse(0, k-1, nums)
self.reverse(k, len(nums)-1, nums)
def reverse(self, start, end, nums):
while (start < end):
tmp = nums[start]
nums[start] = nums[end]
nums[end] = tmp
start += 1
end -= 1
利用python自身的性质:
3、前k项与后k项相交换:
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]