[英]Why is this solution not ideal for “Rotate Array” leetcode question?
leetcode 上的问题是“给定一个数组,将数组向右旋转 k 步,其中 k 是非负数。” 例如“输入:nums = [1,2,3,4,5,6,7],k = 3 Output:[5,6,7,1,2,3,4]”
我在 python 中的解决方案是:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
i = 0
while (i < k):
nums.insert(0, nums.pop())
i+=1
这似乎与任何给定的解决方案都不匹配。 我很好奇这会是什么时间/空间复杂度? 这就是为什么这不是一个给定的解决方案吗? 或者在技术面试中最好不要使用数组函数?
谢谢
以下是 python 中的cut
清单示例,不确定这是否是您正在寻找的解决方案。 您将索引k
处的列表带到列表的length
。 因此,在这种情况下,它的3 to 6
并且您将列表的开头0 to 2
并且您获取列表的第一部分并将其添加到列表的末尾k
的数量。
nums[k:length] = [4,5,6,7]
nums[0:k] = [1,2,3]`
def rotate(nums, k):
length = len(nums)
nums[:] = nums[k:length] + nums[0:k]
print(nums)
number = [1,2,3,4,5,6,7]
rotate(number,3)
这是指向其他一些解释的链接。
https://www.geeksforgeeks.org/python-program-for-program-for-array-rotation-2/
insert
将为每次迭代在内部将所有后续的 n-1 个元素复制 1。 因此,正如 Paul 所说,您的代码具有 O(nk) 的时间复杂度。 因此,即使它回答了问题,但对于大型阵列来说效率太低了。 相反,您可以使用时间复杂度 O(N) 的数组切片。
def rotate_to_right(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
d = len(nums) - k
nums[:]=nums[d:]+nums[:d]
if __name__ == '__main__':
nums = [1,2,3,4,5,6,7]
k = 3
rotate_to_right(nums, k)
print(nums)
结果:
[5, 6, 7, 1, 2, 3, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.