-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtwo_sum.py
31 lines (25 loc) · 825 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
# Solution
from typing import List
# from itertools import combinations
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict_nums = {}
for i, num in enumerate(nums):
if target - num in dict_nums.keys():
return [dict_nums[target - num], i]
else:
dict_nums[num] = i
# slower:
# for (i, value_1), (j, value_2) in combinations(enumerate(nums), 2):
# if value_1 + value_2 == target:
# return [i, j]
#
# return None
# Instantiation to check values
if __name__ == '__main__':
Solve = Solution.twoSum(13, [2, 7, 11, 15], 9) # [0,1]
Solve_1 = Solution.twoSum(16, [3, 2, 3], 6) # [0,2]
Solve_2 = Solution.twoSum(23, [3, 2, 4], 6) # [1,2]
print(Solve)
print(Solve_1)
print(Solve_2)