189. Rotate Array

Posted whatyouthink

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了189. Rotate Array相关的知识,希望对你有一定的参考价值。

Given an array, rotate the array to the right by k steps, where k is non-negative.

Follow up:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

给出一个数组和k,让你把数组往右移动k部,超出数组的部分移动到数组的头部,实际上有很多种解法。

如果要求O1的额外空间的话,做法就有点有意思了。

可以两段先反转,然后再整体反转,举个例子,[1,2,3,4,5,6,7] k= 3 -> [4,3,2,1] [7,6,5] ->[5,6,7,1,2,3,4]

神奇吧

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        k = k % n
        for i in range(0, (n - k + 1) // 2, 1):
            nums[i],  nums[n - k - i - 1] = nums[n - k - i - 1], nums[i]
        for i in range(0, (k + 1) // 2, 1):
            nums[n - k + i], nums[n - i - 1] = nums[n - i - 1], nums[n - k + i]
        for i in range(0, n // 2, 1):
            nums[i], nums[n - i - 1] = nums[n - i - 1], nums[i]
        

 

[1,2,3,4,5,6,7], k = 3

以上是关于189. Rotate Array的主要内容,如果未能解决你的问题,请参考以下文章

189. Rotate Array

LeetCode189. Rotate Array

189. Rotate Array

[Array]189. Rotate Array

189. Rotate Array

189. Rotate Array