LeetCode 题解工作台
轮转数组
给定一个整数数组 nums ,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 示例 1: 输入: nums = [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…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们不妨记数组长度为 ,然后将 对 取模,得到实际需要旋转的步数 。 接下来,我们进行三次翻转,即可得到最终结果:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
示例 1:
输入: nums = [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:
输入:nums = [-1,-100,3,99], k = 2 输出:[3,99,-1,-100] 解释: 向右轮转 1 步: [99,-1,-100,3] 向右轮转 2 步: [3,99,-1,-100]
提示:
1 <= nums.length <= 105-231 <= nums[i] <= 231 - 10 <= k <= 105
进阶:
- 尽可能想出更多的解决方案,至少有 三种 不同的方法可以解决这个问题。
- 你可以使用空间复杂度为
O(1)的 原地 算法解决这个问题吗?
解题思路
方法一:三次翻转
我们不妨记数组长度为 ,然后将 对 取模,得到实际需要旋转的步数 。
接下来,我们进行三次翻转,即可得到最终结果:
- 将整个数组翻转
- 将前 个元素翻转
- 将后 个元素翻转
举个例子,对于数组 , , , 。
- 第一次翻转,将整个数组翻转,得到 。
- 第二次翻转,将前 个元素翻转,得到 。
- 第三次翻转,将后 个元素翻转,得到 ,即为最终结果。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
def reverse(i: int, j: int):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i, j = i + 1, j - 1
n = len(nums)
k %= n
reverse(0, n - 1)
reverse(0, k - 1)
reverse(k, n - 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the approach: extra array method is O(n), in-place cyclic replacement is O(n), and reversal method is O(n). Space complexity ranges from O(n) for the extra array to O(1) for in-place or reversal approaches. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that moves elements efficiently without overwriting unprocessed values.
- question_mark
Pay attention if k exceeds array length and discuss modulo behavior.
- question_mark
Expect discussion on trade-offs between extra memory versus in-place rotation.
常见陷阱
外企场景- error
Overwriting elements before their new position is set in in-place methods.
- error
Failing to account for k values larger than the array size, causing incorrect indexing.
- error
Mismanaging cycle starts, resulting in infinite loops or missing elements during cyclic replacement.
进阶变体
外企场景- arrow_right_alt
Rotate the array to the left instead of the right using similar two-pointer scanning logic.
- arrow_right_alt
Rotate a multidimensional array row-wise or column-wise by k steps.
- arrow_right_alt
Rotate only a subarray segment while leaving other elements intact.