您的位置:首页 > 编程语言 > Python开发

python学习笔记(六)之内置容器dict的妙用

2014-10-17 15:28 411 查看
直接跳过了tuple和其它内置容器,因为大同小异,可以在官方文档查得,只要用心阅读再稍加推敲即可使用,但是这里特别说一下dict,一个我觉得比较特殊的内置容器。

官方文档如此解释dict——A mapping object
maps hashable values
to arbitrary objects.也就是说dict全称dictionary,在其他语言中也称为map。

map的特点是什么?那就是使用键-值(key-value)存储,具有极快的查找速度。

没错,重点就是具有极快的查找速度。为什么dict查找速度这么快?这里可以类比查字典,如果我们使用list存储字典元素,在list中查找元素就等于一页一页的将字典往后翻,元素越多,“翻页”越多,查询越困难也越慢。

但是dict不同,dict等同于建立了索引表(例如字典中的拼音查询),只要查这个字典元素的对应页码,然后直接翻到该页,找到这个字,无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。

用算法复杂度来表示,list的时间复杂度就是O(n),而dict的时间复杂度为O(1)——自然快很多。
附上leetcode一题,很能说明问题。问题如下:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
一开始我解决的方法十分暴力,直接遍历两次num这个list中的元素,分别相加,然后考查是否等于target,代码如下:
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
n = len(num)
index = []
i=0;j=n-1
while target != num[i] + num[j] :
if i<j:
j=j-1
else:
j=n-1
i=i+1
index = [i+1,j+1]
return tuple(index)
提交代码显示TLE,不言而喻,这是一个O(n2)的查找代码,显然是不能通过的。
换用dict类,果然通过:
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict = {}#dict = {"num[i]":i}
for i in range(len(num)):
if target - num[i] in dict:
index1 = i + 1
index2 = dict[target - num[i]] + 1
print (min(index1,index2),max(index1,index2))#actually should use return not print,but it's just for test.
else:
dict[num[i]] = i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: