two sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
https://leetcode-cn.com/problems/two-sum/description/
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
>>> s = Solution()
>>> nums = [3, 2, 4]
>>> target = 6
>>> s.twoSum(nums, target)
[1, 2]
"""
# tmp = [target - i for i in nums]
# for idx, i in enumerate(tmp):
# try:
# idx2 = nums.index(i)
# if idx2 != idx:
# return [idx, idx2]
# except ValueError:
# pass

dic = {}
for idx, num in enumerate(nums):
if target - num in dic:
return [dic[target-num], idx]
dic[num] = idx