题目
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]
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]
解法一
思路
比较暴力无脑的解法,直接先将数组后面k个元素先移动到其他数组,然后将前面nums.length-k个元素向后移动k位,然后再将其他数组的k个元素移回数组前k位即可。时间复杂度O(n),空间复杂度也是O(n)。
代码
class Solution {
public void rotate(int[] nums, int k) {
k%=nums.length;
int[] temp = new int[k];
int len = nums.length;
int tempLen = k-1;
for(int i = len - 1; i > len - 1 - k; i--) {
temp[tempLen] = nums[i];
tempLen--;
}
for(int i = len - 1 - k; i >= 0; i--) {
nums[i+k] = nums[i];
}
for(int i = 0; i < k; i++) {
nums[i] = temp[i];
}
}
}
解法二
思路
先将数组整体逆转一下,然后将前k位逆转一下,再将后nums.length-k位逆转一下。时间复杂度O(n),空间复杂度O(1)。
代码
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);
}
private void reverse(int[] nums, int left, int right) {
while(left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}