LeetCode 189. Rotate Array 题解
Total Accepted: 76162 Total Submissions: 352104 Difficulty: Easy
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.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
public class Solution {
public void rotate(int[] nums, int k) {
//method one
int n = nums.length;
int[] tempNums = new int[n];
for(int l = 0; l < n; l++){
tempNums[l] = nums[l];
}
// 根据k和n的大小进行判断
if ( k > n) {//递归求解
k = k % n;
rotate(nums, k);
} else if (k < n) {
if(k != 0) {
for ( int i = 0; i < k; i++){
nums[i] = tempNums[n - k + i];
}
for ( int j = 0; j < n - k ; j++){
nums[k + j] = tempNums[j];
}
}
}
//method two insert
int n = nums.length;
int temp = 0;
// 根据k和n的大小进行判断
if ( k > n) {//递归求解
k = k % n;
rotate(nums, k);
} else if (k < n){
int[] tempNums = new int[n - k];
for(int l = 0; l < n-k; l++){
tempNums[l] = nums[l];
}
if(k != 0) {
// 从k开始前插到数组
for ( int i = 0; i < k; i++){//控制插入个数
temp = nums[n - k + i];
// for (int j = n - k; j > 0; j-- ){//控制移动个数
// nums[j + i ] = nums[j + i - 1];
// }
nums[i] = temp;
}
for ( int j = 0; j < n - k ; j++){
nums[k + j] = tempNums[j];
}
}
}
//method three time limit
int n = nums.length;
int temp = 0;
// 根据k和n的大小进行判断
if ( k > n) {//递归求解
k = k % n;
rotate(nums, k);
} else if (k < n){
if(k != 0) {
// 从k开始前插到数组
for ( int i = 0; i < k; i++){//控制插入个数
temp = nums[n - k + i];
for (int j = n - k; j > 0; j-- ){//控制移动个数
nums[j + i ] = nums[j + i - 1];
}
nums[i] = temp;
}
}
}