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.
最简单的方法,开一个k
长的数组,先把右边k
个元素存入这个临时数组,然后把数组中的前n-k
右移k
位,再把临时数组的k
个元素存入到原始数组左边。时间复杂度O(n)
,空间复杂度O(k)
。
第二个简单的方法,先实现一个函数,把数组右移一位,调用这个函数k
次即可。时间复杂度O(n*k)
,空间复杂度O(1)
。
第三个方法,先将数组分为两段,前n-k
个为一段,后k
个元素作为第二段,将第一段reverse, 第二段 reverse, 然后将整个数组reverse, 这样经过三轮reverse,就完成了循环右移。时间复杂度O(n)
,空间复杂度O(1)
。
public static void rotateArray(int[] nums,int k)
{
k %= nums.Length;
reverseNums(nums,0,nums.Length-k);
reverseNums(nums, nums.Length - k, nums.Length);
reverseNums(nums, 0, nums.Length);
}
private static void reverseNums(int[]nums,int s,int e)
{
int left = s;
int right = e - 1;
while (left < right)
{
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left++;
right--;
}
}