哪个在Python中效率更高:list.index()或dict.get()

时间:2014-12-31 08:27:08

标签: python

我试图解决a problem on LeetCode.我正在使用Python而我尝试了如下:

def twoSum(self, num, target):
    index0 = 0
    index1 = -1 
    for item in num:
        index0 += 1
        other = target - item
        try:
            index1 = num[index0:].index(other)
            index1 += index0 + 1
        except ValueError:
            continue
        else:
            break
    return index0, index1

但我总能得到结果:Time Limit Exceeded
我的代码的想法是检查列表中是否element(other = target - item),并且我使用了index()方法。

互联网上提供的正确答案如下:

def twoSum(self, num, target):
    length = len(num)
    dic = {}
    for i in xrange(length):
        dic[num[i]] = i
    index0 = -1
    index1 = -1 
    for key in xrange(length):  #not "for key in dic.values():" 
        other = target - num[key]
        index1 = dic.get(other)
        #[1, 2, 3, 4], 4:   2,2 is not the EXPECTED answer.
        if index1 and index1 != key:
            index0 = key + 1
            index1 += 1
            break

    return index0, index1

没关系,但我不明白我的代码有什么问题? list.index()慢于dict.get()吗?

2 个答案:

答案 0 :(得分:7)

  

list.index()慢于dict.get()

总之,是的:list.index()必须扫描列表以查找元素,而dict.get()可以在constant time中完成其工作(即及时)独立于字典的大小)。

因此,第一个算法time complexity是输入大小的二次方(写为O(n ^ 2)),而第二个算法是线性的(O(n)) )。

下图说明了两种增长率之间的差异:

O(n) vs O(n^2)

答案 1 :(得分:1)

字典上的get不执行顺序搜索,基本上它会对键应用散列算法以在内存中查找值。 index执行顺序搜索,因此如果您要查找的项目位于列表的开头,则实际上可能会更快!

在所有条件相同的情况下,字典搜索将保持一致。实际时间取决于使用的算法,理论上可以在python版本之间变化。您可能还想使用set()collections.OrderedDict来考虑您的考试。

你偶然发现了使用词典的一个重要原因。如果您要按位置搜索,则使用列表(或元组),按键搜索然后使用字典。

相关问题