- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwo_sum.py
20 lines (18 loc) · 849 Bytes
/
two_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
classSolution:
deftwoSum(self, nums: List[int], target: int) ->List[int]:
# build a hashtable (by using dictionary)
# note: just store the index (because we need to return the indices)
my_dict= {}
forindexinrange( len(nums) ):
my_dict[ nums[index] ] =index
print(my_dict)
# note: my_target is the complementary number
# just check out if my_target is in the dictionary!!
forindexinrange( len(nums) ):
my_target=target-nums[index]
ifmy_targetinmy_dict:
# be careful: you may not use the same element twice!!!
ifindex==my_dict[my_target]:
pass
else:
return [index, my_dict[my_target] ]