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.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
三段翻转。
Time: O(n)
Space: O(n)
public class Solution {
public void rotate(int[] nums, int k) {
if (nums.length == 0 || k % nums.length == 0) return;
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int l, int r) {
while (l < r) {
int temp = nums[l];
nums[l++] = nums[r];
nums[r--] = temp;
}
return;
}
}
正常做得用个O(n)的数据结构。
GOOGLE有个SHIFT的题,follow up要求in-place without 三段。。
试一试。。
1 2 3 4 5 6 7 = > 5 6 7 1 2 3 4
1 2 3 1 5 6 7 t = 4
1 2 3 1 5 6 4 t = 7
1 2 7 1 5 6 4 t = 3
1 2 7 1 5 3 4 t = 6
1 6 7 1 5 3 4 t = 2
1 6 7 1 2 3 4 t = 5
5 6 7 1 2 3 4..done..
从第一个开始,每次移K个位置,总共移动nums.length个
这个CASE表明移nums.length个不行的。。会回到原点
1 2 3 4 = > 3 4 1 2
1 2 1 4 t = 3
所以回到远点我们就到下一个。。总共还是nums.length
嘿嘿。。做出来了
public class Solution {
public void rotate(int[] nums, int k) {
if (nums.length == 0 || k % nums.length == 0) return;
k %= nums.length;
int done = 0;
for (int i = 0; i < k; i++) {
int j = i;
int tempVal = nums[i];
while (done < nums.length) {
int tempJ = (j + k) % nums.length;
int temp = nums[tempJ];
nums[tempJ] = tempVal;
tempVal = temp;
j = tempJ;
done++;
if (j == i) break;
}
}
}
}