刷算法题心得:python 中遍历字典key的时候用 dic.keys() 比 dic 要慢

# 慢
words_dic = {}
for word in words:
    if word in words_dic.key():
        words_dic[word] += 1
    else:
        words_dic[word] = 1


# 快
words_dic = {}
for word in words:
    if word in words_dic:
        words_dic[word] += 1
    else:
        words_dic[word] = 1

刷 leetcode 的时候发现自己提交的代码总是比示例代码要多200ms,最后发现把 .keys() 删掉就可以了!!!

你可能感兴趣的:(Python精修,leetcode,python,leetcode)