一、题目
题目链接:https://leetcode.com/problems/two-sum/#/description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
二、思路
1. 最初的想法是使用两层遍历,外层循环i从0 - n-1,内层循环j从i - n-1,当符合条件时返回[i, j]。该算法时间复杂度为O(n^2),空间复杂度为O(1)。Python代码如下:class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if(nums[i]+nums[j]==target):
return [i, j]
return False
2. 后来参考了leetcode中的时间复杂度最优答案(为O(n)),使用了python中的字典,将两层嵌套变为线性查找。使用字典dict,对于每个nums中的元素nums[i],查看target - nums[i]是否在字典dict中,如果在,则直接返回[i, dict[target - nums[i]],如果不在,则把 target - nums[i] : i 存入dict。
这样的if-else结构可以把本来需要先存入字典再查找的两遍遍历整合为一遍。
另外target - nums[i]作为key的好处是便于查找,而且即使出现了两个元素值相同的情况,可以把dict中的i替换掉。
代码如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(0, len(nums)):
if nums[i] in dict.keys():
return [i, dict[nums[i]]]
else:
dict[target - nums[i]] = i
return False
三、Python的dict
1. 操作
参考:http://blog.csdn.net/wangran51/article/details/8440848
|
2. dict原理
参考:https://foofish.net/python_dict_implements.html
字典类型是Python中最常用的数据类型之一,它是一个键值对的集合,字典通过键来索引,关联到相对的值,理论上它的查询复杂度是 O(1)。
哈希表 (HASH TABLES)
哈希表(也叫散列表),根据关键值对(Key-value)而直接进行访问的数据结构。它通过把key和value映射到表中一个位置来访问记录,这种查询速度非常快,更新也快。而这个映射函数叫做哈希函数,存放值的数组叫做哈希表。 哈希函数的实现方式决定了哈希表的搜索效率。具体操作过程是:
数据添加:把key通过哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里。
数据查询:再次使用哈希函数将key转换为对应的数组下标,并定位到数组的位置获取value。
但是,对key进行hash的时候,不同的key可能hash出来的结果是一样的,尤其是数据量增多的时候,这个问题叫做哈希冲突。如果解决这种冲突情况呢?通常的做法有两种,一种是链接法,另一种是开放寻址法,Python选择后者。