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.
此题想出来的第一个解题思路是整体旋转一次,然后0-(k-1)旋转一次,后面的数组元素再旋转一次,代码如下:
public class Solution {
public void rotate(int[] nums, int k) {
k = k%(nums.length);
rotatehelper(nums,0,nums.length-1);
rotatehelper(nums,0,k-1);
rotatehelper(nums,k,nums.length-1);
}
public void rotatehelper(int[] nums,int left,int right){
int l = left;
int r = right;
while(l<r){
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
}
第二种方法是把原来的数组元素放到排好序的新数组里面,然后新数组的值赋值回原数组里面,代码如下:
public class Solution {
public void rotate(int[] nums, int k) {
int[] num = new int[nums.length];
for(int i=0;i<nums.length;i++){
num[(i+k)%(nums.length)] = nums[i];
}
for(int i=0;i<num.length;i++){
nums[i] = num[i];
}
}
}