leetcode 189. Rotate Array 2018-
2018-03-13 本文已影响0人
美雅may
题目如下
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]
给定一个数组,和一个数字k,将数组末尾的数字移到开头
Python 解题
class Solution:
def rotate(self, nums, k):
n = len(nums) - k ###算出到哪个 元素为止,需要将后面的元素移到开头
nums[:] = nums[n:] + nums[:n] ###将后面的元素移到开头,后面补上开头的元素