# 189. Rotate Array 轮转数组

@TOC

## # 题目描述

Rotate an array of n elements to the right by k steps.

``````For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
``````

Note:

• Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
• Could you do it in-place with O(1) extra space?

## # 解题方法

### # 切片

1. k可能很大，也就是会旋转多次
2. 原地翻转

``````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.
"""
while k > len(nums):
k -= len(nums)
changed = nums[-k:] + nums[:-k]
for i in range(len(changed)):
nums[i] = changed[i]
``````

``````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]
``````

### # 递归

``````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 %= N
self.reverse(nums, 0, N - 1);
self.reverse(nums, 0, k - 1);
self.reverse(nums, k, N - 1);

def reverse(self, nums, start, end):
while start <= end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
``````

## # 日期

2018 年 2 月 5 日 2018 年 11 月 29 日 —— 时不我待