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

时间:2021-02-25 18:57:31

标签: python arrays

leetcode 上的问题是“给定一个数组,将数组向右旋转 k 步,其中 k 为非负数。” 例如 "输入:nums = [1,2,3,4,5,6,7], k = 3 输出:[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

这似乎与任何给定的解决方案都不匹配。我很好奇这的时间/空间复杂度是多少?这就是为什么这不是给定的解决方案的原因吗?或者在技术面试中最好不要使用数组函数?

谢谢

2 个答案:

答案 0 :(得分:0)

这里是 Python 中 cut 列表的示例,不确定这是否是您正在寻找的解决方案。您将索引 k 处的列表带到列表的 length。因此,在这种情况下,它的 3 to 6 并取列表 0 to 2 的开头,取列表的第一部分,然后按 k 的数量将其添加到列表的末尾。< /p>

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/

答案 1 :(得分:0)

myUniqueList = [] def myFunction(arr: list): if len(arr) != len(set(arr)): return False else: [myUniqueList.append(i) if i not in myUniqueList else None for i in arr] print(myUniqueList) return True 将在每次迭代时在内部将所有后续 n-1 元素复制 1。因此,正如保罗所说,您的代码的时间复杂度为 O(nk)。因此,即使它回答了这个问题,但对于大型阵列来说效率太低了。相反,您可以使用时间复杂度为 O(N) 的数组切片。

insert

结果:

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)
相关问题