原題
給出一個n個元素的數(shù)組,向右位移k位。比如 n = 7 and k = 3, 已知數(shù)組為[1,2,3,4,5,6,7] 旋轉(zhuǎn)之后為 [5,6,7,1,2,3,4].
解題思路
- 跟LintCode中旋轉(zhuǎn)string是一樣的思路,三步翻轉(zhuǎn)法
完整代碼
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