leetcode1-两数之和
思路:
1.使用暴力,两遍循环数组;
2.使用哈希表(字典),一遍循环即可。将数作为key,对应的索引作为value。注意a[b]!=i条件的限制
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a={}
for i ,j in enumerate(nums):
a[j]=i
for i,j in enumerate(nums):
b=target-j
if b in a and a[b]!=i:
return [i,a[b]]