[leetcode] 189. Rotate Array

题目

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

Example 1:

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

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [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]

Constraints:

  • 1 <= nums.length <= 10^5

  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 105

Follow up:

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

思路

由于旋转一圈等于没旋转,因此首先把步长k对数组长度取模。接着由数组复制一个新数组,将新数组中的元素以k为边界映射至旧数组。

还有一个神奇算法,逆转数组,再逆转0到k-1,再逆转k到n-1,即可完成该题。

代码

python版本:

# 
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k=k%len(nums)
        tmp=nums.copy()
        for i in range(len(nums)):
            nums[(i+k)%len(nums)]=tmp[i]

# 神奇算法
def reverse(nums,start,end):
    while start<end:
        nums[start],nums[end]=nums[end],nums[start]
        start+=1
        end-=1

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k=k%len(nums)
        reverse(nums,0,len(nums)-1)    
        reverse(nums,0,k-1)
        reverse(nums,k,len(nums)-1)

posted @ 2022-02-24 23:52  frankming  阅读(17)  评论(0编辑  收藏  举报