美文网首页
189. Rotate Array

189. Rotate Array

作者: 我只是一把剑 | 来源:发表于2018-11-28 10:19 被阅读0次

    Given an array, rotate the array to the right byksteps, wherekis non-negative.

    Example 1:

    Input:[1,2,3,4,5,6,7]andk= 3Output:[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]

    Example 2:

    Input:[-1,-100,3,99]andk= 2Output:[3,99,-1,-100]Explanation:rotate 1 steps to the right: [99,-1,-100,3]rotate 2 steps to the right: [3,99,-1,-100]

    最简单的思想,暴力解法:数组pop出来后再insert进去,当然,这样复杂度O(n*k)和耗时自然很高,虽然简单

    class Solution(object):

    def rotate(self, nums, k):

    """

    :type nums: List[int]

    :type k: int

    :rtype: void Do not return anything, modify nums in-place instead.

    """

    for i in range(0,k):

    r=nums.pop()

    nums.insert(0,r)

    相关文章

      网友评论

          本文标题:189. Rotate Array

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