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.
思路:
- 用另一个数组存储,rotate后该数组的样子,然后再依次赋值给原数组。
public void rotate1(int[] nums, int k) {
if (nums == null || nums.length <= 1) {
return;
}
int[] rnums = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
rnums[(i+k)%nums.length] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = rnums[i];
}
}
- 先reverse整个数组,然后reverse前k个,再reverse后面的部分。
public void rotate(int[] nums, int k) {
if (nums == null || nums.length <= 1) {
return;
}
//k > n or k < n
int len = nums.length;
k %= len;
reverse(nums, 0, len - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, len - 1);
}
private void reverse(int[] nums, int start, int end) {
if (start >= end) {
return;
}
while (start < end) {
int tmp = nums[start];
nums[start++] = nums[end];
nums[end--] = tmp;
}
}