189. Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
翻译:将有n个元素的数组向右旋转k步。
如:n=7,k=3时,数组 [1,2,3,4,5,6,7]旋转为
[5,6,7,1,2,3,4]。
注意:
用尽量多的方法来解决该问题,至少有三种不同方法。
大神danny6514解法:
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
本质上来看,旋转k位,无非是把最后k位挪到最前面,作者用
k %= nums.length处理k大于数组长度的情况。
作者的思想是先全部反转,再分别把两部分(0,k-1和k,nums.length-1)反转,这样最后相当于把后面的k位挪到了前面。和我的算法相比,没有占用额外空间
class Solution {
public void rotate(int[] nums, int k) {
int[] newNum=new int[nums.length];
for (int i=0;i<nums.length;i++) {
newNum[(i+k)%nums.length]=nums[i];
}
for(int i=0;i<nums.length;i++) {
nums[i]=newNum[i];
}
}
}