0189. 轮转数组 #22
Replies: 15 comments 2 replies
-
具体步骤3是否应该为[k,n-1]位置上的元素进行翻转 |
Beta Was this translation helpful? Give feedback.
-
嗯嗯。应该是 [k, n-1]。 感谢指正呀 |
Beta Was this translation helpful? Give feedback.
-
写的很好,mark,按照这个顺序刷题了 |
Beta Was this translation helpful? Give feedback.
-
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
start=0
end=len(nums)-1
length=end - start +1
direction = 1 #0 for going left, 1 for going right
k = k % length
while(k != 0):
# if k > length/2, rotate to opposite direction
if 2* k > length:
direction ^= 1
k = length - k
#swap k number between start and end
for i in range(k):
tmp=nums[start + i]
nums[start + i] = nums[end - k + 1 + i]
nums[end- k + 1 + i] = tmp
start += k * direction
end -= k * (direction^1)
length= end - start + 1
k = k % length 自己想了个办法,时间复杂度也是O(n)但是慢一点,感觉我这个cycle数会更小一点来着,平均1n个cycle.可以参考看看为什么嘛 |
Beta Was this translation helpful? Give feedback.
-
我觉得这样的话 是很简便的 def Wheel_Array(array, k):
|
Beta Was this translation helpful? Give feedback.
-
def rotate(nums, k):
我在pycharm上能实现 但在leetcode上报错 有人帮我看看吗! 感谢 |
Beta Was this translation helpful? Give feedback.
-
leetcode 上计算的是运行时间,只要复杂度一致,快一点慢一点不用太在意。 |
Beta Was this translation helpful? Give feedback.
-
这道题并不需要返回数组,而是需要直接在原数组上进行修改。 |
Beta Was this translation helpful? Give feedback.
-
可以用切片[::-1]代替翻转函数,会方便些 |
Beta Was this translation helpful? Give feedback.
-
为什么这样会改变外部的nums,我用 |
Beta Was this translation helpful? Give feedback.
-
请问为何需要 k = k % n 这一步? |
Beta Was this translation helpful? Give feedback.
-
for i in range(k): |
Beta Was this translation helpful? Give feedback.
-
class Solution(object): |
Beta Was this translation helpful? Give feedback.
-
直接把最后的k个元素slice一下放到最前面,然后删掉最后的k个元素,这样时间是O(k) [插入耗时],空间是O(1) class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
if k == 0 or n <=1:
return
nums[:0] = nums[-k:]
del nums[-k:] |
Beta Was this translation helpful? Give feedback.
-
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if k == 0: # no need to move
return
k = k % len(nums)
index = len(nums) - k
nums[:] = nums[index:] + nums[:index] |
Beta Was this translation helpful? Give feedback.
-
0189. 轮转数组 | 算法通关手册
要求:将数组中的元素向右移动 k 个位置。
说明:
https://algo.itcharge.cn/Solutions/0100-0199/rotate-array
Beta Was this translation helpful? Give feedback.
All reactions