残暴解法:o(n²)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
tips:
1.从第一个整数开始,逐个配对
2.成功便输出,失败便下一个
"""
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
return
进化版本:o(n)
思考角度:本质上是查找target-x,散列表平均查找长度与n无关,在查找过程中,不停扩充散列表,直到找到为止
class Solution:
def twoSum(self, nums, target):
hashtable = dict() # hashtable里面放的是没有配对的一半
for i, num in enumerate(nums): # enumerate枚举(下标,值)
print('i = %d, num = %d' % (i, num))
if target - num in hashtable: # 看key有没有
return [hashtable[target - num], i]
print("nums[%d] = %d" % (i, nums[i]))
hashtable[nums[i]] = i # {2:0}
print(hashtable)
return[]
耗时:1h