Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1, 2, 3, 4, 5, 6, 7] and k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Explanation:
rotate 1 step to the right: [7, 1, 2, 3, 4, 5, 6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
public class Solution {
public void rotate(int[] nums, int k) {
int[] rotated = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
rotated[(i + k) % nums.length] = nums[i]; // compute new index
}
// place rotated result back to nums
for (int i = 0; i < nums.lenght; i++) {
nums[i] = rotated[i];
}
}
}
public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int count = 0;
for (int start = 0; count < nums.length; start++) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % nums.length;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
}
Complexity Analysis:
Time Complexity: O(n)
Space Complexity: O(1)
方案三:
思路
一种更巧妙的方法则需要我们仔细观察旋转前后的数组区别。举例如下,假设我们n=7, k=3:
Original List : 1 2 3 4 5 6 7
After rotating k positions : 5 6 7 1 2 3 4
Original List : 1 2 3 4 5 6 7
After reversing all numbers : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result
解答
public class Solution {
public void rotate(int[] nums, int k) {
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 start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}