个人思路:每个元素向后移k位,超出数组长度的用mod操作重新计数,需要额外的数组空间
python
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
list = [0]*(len(nums))
for i in range(0, len(nums)):
list[(i+k)%(len(nums))] = nums[i]
nums[:] = list
java
class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] list = new int[len];
for(int i=0;i<len;i++){
list[(i+k)%len] = nums[i];
}
for(int i=0;i<len;i++){
nums[i] = list[i];
}
}
}
C
void rotate(int* nums, int numsSize, int k) {
int list[numsSize];
for(int i=0;i<numsSize;i++){
list[(i+k)%numsSize] = nums[i];
}
for(int i=0;i<numsSize;i++){
nums[i] = list[i];
}
}
额外思路:两次翻转,先翻转全部,再反转0到k-1和k-1到最后
python有自带翻转函数reversed
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
m = k%length
nums[:] = nums[::-1]
nums[m:length] = reversed(nums[m:length])
nums[0:m] = reversed(nums[0:m])