题目:
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.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
方案一:
构造新的数组,把nums的值,从nums.length-1-k位开始顺序填充(到头后继续,直到nums.length-1-k位);
代码:
public void rotate(int[] nums, int k) {
k %= nums.length;
List<Integer> newNums = new ArrayList<Integer>(nums.length);
for (int i = nums.length - k; i < nums.length; i++) {
newNums.add(nums[i]);
}
for (int i = 0; i < nums.length - k; i++) {
newNums.add(nums[i]);
}
for (int i = 0; i < nums.length; i++) {
nums[i] = newNums.get(i);
}
}
前半部分反转,后半部分反转,再将整体反转
代码:
public void rotate2(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length-1-k);
reverse(nums,nums.length-k,nums.length-1);
reverse(nums,0,nums.length);
}
// [s,e]
public void reverse(int[] list, int s, int e) {
if(list == null || list.length == 0 || s>= list.length || e >= list.length)
return;
int element;
for(;s<e;){
element = list[s];
list[s] = list[e];
list[e] = element;
s++;
e--;
}
}