189. Rotate Array

2018-11-28  本文已影响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)

上一篇下一篇

猜你喜欢

热点阅读