原题
给出一个n个元素的数组,向右位移k位。比如 n = 7 and k = 3, 已知数组为[1,2,3,4,5,6,7] 旋转之后为 [5,6,7,1,2,3,4].
解题思路
- 跟LintCode中旋转string是一样的思路,三步翻转法
完整代码
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.
"""
if len(nums) == 0:
return
k %= len(nums)
self.helper(nums, len(nums) - k, len(nums) - 1)
self.helper(nums, 0, len(nums) - k - 1)
self.helper(nums, 0, len(nums) - 1)
def helper(self, nums, i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1