时间复杂度为O(n)
code:
class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length;
k=k%n;
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[(i+k)%n]=nums[i];
}
for(int i=0;i<n;i++){
nums[i]=arr[i];
}
}
}
参考答案 进行三次翻转 空间复杂度O(1)
code:
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 += 1;
end -= 1;
}
}
}
作者:御三五 🥇