《编程之美》P221
Rotate an array ofn elements to the right byk steps.
For example, withn = 7 andk = 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 differentways to solve this problem.
Hint:
Could you do it in-place with O(1) extra space?
Related problem:Reverse Words in a String II
Credits:
Special thanks to @Freezen for addingthis problem and creating all test cases.
解法一:将后k位翻转,再将前n-k位翻转,最后翻转整个数组,即得到结果
public class Solution {
public void rotate(int[] nums, int k) {
//先判断输入参数是否合法
if((nums != null) && (nums.length > 0) && (k > 0))
{
k %= nums.length;
if(k != 0)
{
//颠倒后k个数字
reverse(nums,nums.length - k,nums.length - 1);
//颠倒前n-k个数字
reverse(nums,0,nums.length - k - 1);
//颠倒整个数组
reverse(nums,0,nums.length - 1);
}
}
}
//颠倒一个数组中的所有元素
private void reverse(int[] nums,int start,int end)
{
for(int i = start ; i * 2 <= (start+end); i++)
{
int temp = nums[i];
nums[i] = nums[start+end-i];
nums[start+end-i] = temp;
}
}
}
解法二:将后面k个数分别按倒序移动至头部
即 [1,2,3,4,5,6,7]
k=1: [7,1,2,3,4,5,6]
k=2: [6,7,1,2,3,4,5]
k=3: [5,6,7,1,2,3,4]
明显时间复杂度性能较差
public class Solution {
public void rotate(int[] nums, int k) {
//先判断输入参数是否合法
if((nums != null) && (nums.length > 0) && (k > 0))
{
k %= nums.length;
while(k != 0)
{
reverse_head(nums);
}
}
}
//将数组最后一个数字移至头部
private void reverse_head(int[] nums)
{
int tail = nums[nums.length - 1];
for(int j = nums.length - 1;j > 0; j --)
{
nums[j] = nums[j - 1];
}
nums[0] = tail;
}
}