-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtwo_sum.py
38 lines (32 loc) · 938 Bytes
/
two_sum.py
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
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python
# Created by Bruce yuan on 18-1-23.
class Solution(object):
def twoSum(self, nums, target):
i = 0
q = 0
for i in range(0, len(nums)):
m = target - nums[i]
if m in nums:
q = nums.index(m)
if q != i:
break
return [i, q]
class Solution2(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for index, item in enumerate(nums):
# if d.get(target - item, None) or d.get(target - item, None) == 0:
if (target - item) in d:
return [d.get(target - item), index]
else:
d[item] = index
if __name__ == '__main__':
s = Solution()
print(s.twoSum([6, 2, 4], 6))
s = Solution2()
print(s.twoSum([6, 2, 4], 6))