题目:
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.
思路与步骤:
思路1:
用一个 List 存储变换好顺序的数组,然后赋值给原数组;
思路2:
用一个长度为 k 的数组存储变换好的数组的前半截,后半截直接在原数组上修改;
思路3:
写一个 reverse() 函数,然后用三步逆转实现。
编程实现:
Solution-1:
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return;
k = k % len;
List<Integer> numlist = new ArrayList<Integer>();
for(int i=0; i<k; i++) numlist.add(nums[nums.length-k+i]);
for(int i=k; i<nums.length; i++) numlist.add(nums[i-k]);
for(int i=0; i<nums.length; i++) nums[i] = numlist.get(i);
}
}
Solution-2:
public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length <= 1) return;
int step = k % nums.length;
int[] tmp = new int[step];
for(int i=0; i<step; i++) tmp[i] = nums[nums.length - step + i];
for(int i=nums.length-step-1; i>= 0; i--) nums[i + step] = nums[i];
for(int i=0; i<step; i++) nums[i] = tmp[i];
}
}
Solution-3:
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return;
k = k % len;
reverse(nums, 0, len-1);
reverse(nums, 0, k-1);
reverse(nums, k, len-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--;
}
}
}