题目概述:
题目注意点:
使用字典存储下标的方式:
- 优势:查找是否存在其中,dict速度比List遍历要快很多倍。
python中in在list和dict中查找效率比较
解题思路:
target依次减去nums列表中的元素,看看是否存在dict中,如果不存在,就吧这个元素和下标加入到dict中。存在就返回两个下标。
字典存放技巧:list的值当key,下标当做val
完整代码:
class Solution:
def twoSum(self,nums,target):
d = {}
n = len(nums)
for x in range(n):
if target - nums[x] in d:
return d[target-nums[x]],x
else:
d[nums[x]] = x
作者:chanpin
链接:https://leetcode-cn.com/problems/two-sum/solution/wo-shi-pythoncai-ji-liang-shu-zhi-he-de-3ge-jie-fa/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。