题目:
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.
思路:
- 题意:要求对给定长度的整形数组n进行平移,给定k,就平移3个位置(循环)
- 要求是在o(1)的空间,不能考虑数组的复制了,根据算法,这个平移转化为逆序。reverse(nums,0,n-k-1),reverse(nums,n-k,n-1),reverse(nums,0,n-1)等价,写一个reverse的函数。
代码:
public class Solution {
public void reverse(int[] nums,int start,int end){
while(start < end){
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
public void rotate(int[] nums, int k) {
if(nums.length == 0){
return;
}
int n = nums.length;
k = k%n;
reverse(nums,0,n-k-1);
reverse(nums,n-k,n-1);
reverse(nums,0,n-1);
}
}