简体   繁体   English

为什么这个解决方案不适合“旋转数组”leetcode 问题?

[英]Why is this solution not ideal for “Rotate Array” leetcode question?

the question on leetcode says "Given an array, rotate the array to the right by k steps, where k is non-negative." leetcode 上的问题是“给定一个数组,将数组向右旋转 k 步,其中 k 是非负数。” for example "Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]"例如“输入:nums = [1,2,3,4,5,6,7],k = 3 Output:[5,6,7,1,2,3,4]”

My solution in python was:我在 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

This does not seem to match any of the given solutions.这似乎与任何给定的解决方案都不匹配。 I am curious what the time/space complexity of this would be?我很好奇这会是什么时间/空间复杂度? Is that why this is not a given solution?这就是为什么这不是一个给定的解决方案吗? OR is it best to not use array functions in tech interviews?或者在技术面试中最好不要使用数组函数?

Thanks谢谢

Heres on example of cut list in python, not sure if this is the solution you are looking for.以下是 python 中的cut清单示例,不确定这是否是您正在寻找的解决方案。 Where you take the list at index k to the length of the list.您将索引k处的列表带到列表的length So in this case its 3 to 6 and you take beginning of list 0 to 2 and you take the first part of the list and you add it to the end of the list by amount of k .因此,在这种情况下,它的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)

Here is a link to some other explantions.这是指向其他一些解释的链接。

https://www.geeksforgeeks.org/python-program-for-program-for-array-rotation-2/ https://www.geeksforgeeks.org/python-program-for-program-for-array-rotation-2/

insert will internally copy all the consequent n-1 elements by 1 for each iteration. insert将为每次迭代在内部将所有后续的 n-1 个元素复制 1。 Hence, your code is of time complexity O(nk) as Paul said.因此,正如 Paul 所说,您的代码具有 O(nk) 的时间复杂度。 Thus, even though it answers the question, it is too inefficient for a large array.因此,即使它回答了问题,但对于大型阵列来说效率太低了。 Instead, you could use array slicing, which is of time complexity O(N).相反,您可以使用时间复杂度 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)

Result:结果:

[5, 6, 7, 1, 2, 3, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM