189、Rotate Array 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 steps 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]
思路:
翻转数组有很多种做法,这里就只说一种 time:O(n) space:O(1),思路就是经过三次翻转数组,达到只翻转到k的目的。
代码:
java:
class Solution {
public void rotate(int[] nums, int k) {
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) {
int temp = 0;
while (start < end) {
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
go:
func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums, 0, len(nums)-1)
reverse(nums, 0, k-1)
reverse(nums, k, len(nums)-1)
}
func reverse(nums []int, start, end int) {
for ; start < end; {
nums[start], nums[end] = nums[end], nums[start]
start++
end--
}
}