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

2019-01-31  本文已影响0人  失业生1981

Array

189. Rotate Array

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

Solutions

最简单的想法是把后面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.
        """
        nums[:]=nums[len(nums)-k:]+nums[:len(nums)-k]

另一种实现的方式是将最后一个元素放到第一个,重复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
上一篇下一篇

猜你喜欢

热点阅读