美文网首页
每天(?)一道Leetcode(16) Rotate Arra

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

作者: 失业生1981 | 来源:发表于2019-01-31 19:52 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:每天(?)一道Leetcode(16) Rotate Arra

          本文链接:https://www.haomeiwen.com/subject/brelsqtx.html