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]
.
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
S1: reverse 3 times.
public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
if(k==0 || nums==null || nums.length==0) return;
int len = nums.length;
reverseNums(nums, 0, len-1-k);
reverseNums(nums, len-k, len-1);
reverseNums(nums, 0, len-1);
}
public void reverseNums(int[] nums, int begin, int end){
// begin and end are real array indexes: from 0 to nums.length-1
if(end<=begin) return;
int len = end-begin+1;
for(int i=begin; i<begin+len/2;i++){
int temp = nums[i];
nums[i] = nums[2*begin+len-1-i];
nums[2*begin+len-1-i] = temp;
}
}
}