Given an integer array nums, 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 step 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]
这道题要求将数组向右平移 k 步,核心是把末尾的 k 个元素搬到数组前面,同时保持其相对顺序不变。面试中常见的做法是先对 k 取模,避免当 k 大于数组长度时重复旋转;然后可以用额外数组直接拼接,也可以用“三次翻转”在原地完成,兼顾时间和空间效率。对于示例 [1,2,3,4,5,6,7] 和 k=3,最终结果是 [5,6,7,1,2,3,4]。
正文完