题目描述:
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].
解题思路:
数组向右进行旋转,每旋转n次恢复原状,所以k要mod n得到简化后的旋转次数。最先想到的是新建一个整型数组,分两部分进行,存储旋转后的数组,最后修改原数组nums中的顺序。
代码:
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
int[] result = new int[n];
int num = k % n;
for (int i = n - num, j = 0; i < n && j<n; i++,j++){
result[j] = nums[i];
}
for (int i = 0,j = num; i<n && j<n;i++,j++){
result[j] = nums[i];
}
for(int i = 0;i<n;i++){
nums[i] = result[i];
}
}
}
改进:
由于新建了一个数组,造成了内存空间的占用,想办法仅仅利用数组nums进行旋转。基本的想法是:例如数组为 nums = [1,2,3,4,5,6,7] 且 k = 3。首先,我们翻转[1,2,3,4],变为[4,3,2,1];然后我们翻转[5,6,7],变为[7,6,5];最后我们翻转整个数组,[4,3,2,1,7,6,5] —> [5,6,7,1,2,3,4].
代码:
class Solution {
public void rotate(int[] nums, int k) {
if(nums == null || nums.length <2){
return;
}
int num = k % nums.length;
reverse(nums,0,nums.length-1-num);
reverse(nums,nums.length-num,nums.length-1);
reverse(nums,0,nums.length-1);
}
public void reverse(int[] nums, int i,int j){
while(i<j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
}