在* in *

时间:2019-05-11 05:10:03

标签: python dictionary time-complexity

问题:

给出一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标。

您可以假设每个输入都只有一个解决方案,并且您可能不会两次使用相同的元素。

我的解决方案:

我所做的是建立一本字典并遍历列表 给定的数字(O(n))。在执行此操作时,我还在检查字典(0(1))中是否存在所需的数字。因此,该解决方案的时间复杂度为O(n)。

我的解决方案有效,但是我是Python的新手,我不理解cache.keys()中 nums [i]的时间复杂性。在编写代码时,我以为cache.keys()中的 nums [i]会花费O(n)时间才能在键列表中找到nums [i],从而使时间复杂度为O( n ^ 2)。但是我的解决方案的结果看起来像是绕过O(n)时间。这使我相信cache.keys()中的 nums [i]花费O(1)时间。我想知道这是否正确,是否有人可以解释这是怎么回事。

    def twoSum(self, nums, target):
        cache = {}
        for i in range(len(nums)):
            b = target - nums[i]

            if nums[i] in cache.keys():
                return [i, cache[nums[i]]]

            cache[b] = i;

runtime results

谢谢:)

1 个答案:

答案 0 :(得分:0)

字典被实现为哈希表/映射,其哈希表的平均性能为O(1)。在内部,它们具有与set相同的实现。

要进一步提高性能,请替换

if nums[i] in cache.keys():

使用

if nums[i] in cache:

此外,您可以使用enumerate进行改进(这是更加Pythonic的):

def twoSum(self, nums, target):
    cache = {}
    for i, x in enumerate(nums):
        b = target - x

        if x in cache:
            return [i, cache[x]]

        cache[b] = i;