LeetCode 189. 旋转数组 Rotate Array

本文深入解析数组旋转问题,提供多种解决方案,重点介绍一种利用三次反转实现原地旋转的方法,适用于k为非负数的情况,同时满足O(1)的空间复杂度要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Table of Contents

中文版:

英文版:

My answer:

解题报告:


中文版:

给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:

输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:

尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。

英文版:

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

Example 1:

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]
Example 2:

Input: [-1,-100,3,99] and 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]
Note:

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?

My answer:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        k = k % n
        # 上一步是为了 Corner case: [1,2,3,4,5,6]   k = 11 的情况
        
        self.helper(nums,0, n-k-1)
        self.helper(nums,n-k,n-1)
        self.helper(nums,0,n-1)
    
    
    def helper(self,nums,start,end):
        while start < end:
            temp =  nums[start]
            nums[start] = nums[end]
            nums[end] = temp
            start += 1
            end -= 1
        # print(nums)
"""
知识点:
1、nums[0:n-k-1] 截取 list 片段是新生成一个 list,不改变原来的list
"""

解题报告:

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

三步翻转法:

1、翻转 0 到 n-k-1: 4321 567

2、翻转 n-k 到 n-1: 4321 765

3、翻转 0 到 n-1:  5671234

此方法同样适用于翻转字符串题目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值