Rotate Array

189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

给一个数组和一个整数k, 把数组往右移k位. 需要注意的是k有可能比数组的长度要大

思路

首先要知道的是要移动多少位, 然后把后k位保存下来, 然后把它贴到前面去.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def rotate(nums, k):
k = k % len(nums)
left = nums[len(nums)-k:]

i = len(nums)-k-1
j = len(nums) - 1
while i >= 0:
nums[j] = nums[i]
i -= 1
j -= 1

i = 0
while i < len(left):
nums[i] = left[i]
i += 1

时间复杂度

$O(n)$

EOF