0189. Rotate Array (E)
Rotate Array (E)
题目
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?
题意
将给定数列的指定后半部分与前半部分换位,得到新数组。
思路
最经典的\(O(1)\)空间方法是翻转法:先将左子数组翻转,再将右子数组翻转,最后将整个数组翻转,得到的就是目标数组。
比较直接的是按照步骤一个一个移动元素,或者使用额外数组先将右子数组保存下来再处理。
官方解答还提供了一种循环替换法:以一个元素为起点,直接将该元素放在它应在的位置上,并将该位置上原本的元素继续按上述操作放在下一个位置上,直到回到起点完成一次循环,接着更换起点重复操作即可。当这种放置进行了n次后,所有元素都已经在它应在的位置上。该方法是对暴力法的一种优化。
代码实现
Java
翻转法
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1 - k);
reverse(nums, nums.length - k, nums.length - 1);
reverse(nums, 0, nums.length - 1);
}
private void reverse(int[] nums, int left, int right) {
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}
暴力法
class Solution {
public void rotate(int[] nums, int k) {
for (int i = 0; i < k; i++) {
int pre = nums[nums.length - 1];
for (int j = 0; j < nums.length; j++) {
int temp = nums[j];
nums[j] = pre;
pre = temp;
}
}
}
}
额外数组
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int[] temp = Arrays.copyOfRange(nums, nums.length - k, nums.length);
for (int i = nums.length - 1; i >= k; i--) {
nums[i] = nums[i - k];
}
for (int i = 0; i < k; i++) {
nums[i] = temp[i];
}
}
}
循环替换
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int count = 0;
// 当count==nums.length时,说明所有元素都已经在它应在的位置上
for (int i = 0; count < nums.length; i++) {
int j = i;
int pre = nums[j];
do {
int next = (j + k) % nums.length;
int temp = nums[next];
nums[next] = pre;
pre = temp;
j = next;
count++;
} while (j != i); // 回到起点,说明一次循环完成
}
}
}
JavaScript
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
k %= nums.length
nums
.slice(0, nums.length - k)
.reverse()
.concat(nums.slice(nums.length - k).reverse())
.reverse()
.forEach((v, i) => (nums[i] = v))
}