每天(?)一道Leetcode(16) Rotate Array

Array

189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.
即给定一个数组,和正整数,将数组元素向右移动步
举个例子:
Input: and
Output:
Explanation:
rotate 1 steps to the right:
rotate 2 steps to the right:
rotate 3 steps to the right:

Solutions

最简单的想法是把后面个元素放到前面,前面的放到后面

class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums[:]=nums[len(nums)-k:]+nums[:len(nums)-k]

另一种实现的方式是将最后一个元素放到第一个,重复次

class Solution:
    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>0:
            nums.insert(0,nums.pop())
            k-=1

你可能感兴趣的:(每天(?)一道Leetcode(16) Rotate Array)