Python代码
哈希查找
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={}
for index,num in enumerate(nums):
another_num=target-num
if another_num in hashmap:
return [hashmap[another_num],index]
hashmap[num]=index
return None
暴力破解
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]+nums[j] == target and i != j :
return [i,j]
return None
总结
1、使用字典便于查找和添加。哈希查找复杂度为O(1),相较于暴力破解效率更高。
2、题目关键在于,能否意识到将两数相减添加到字典中,便于以后查找的操作。