- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwo_sum_II.py
20 lines (18 loc) · 902 Bytes
/
two_sum_II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
classSolution:
deftwoSum(self, numbers: List[int], target: int) ->List[int]:
# build a hash table (by using dictionary)
my_dict= {}
forindexinrange( len(numbers) ):
my_dict[ numbers[index] ] =index
# find the complementary number (and its index)
forindexinrange( len(numbers) ):
my_target=target-numbers[index]
ifmy_targetinmy_dict:
# note: you may not use the same element twice
ifindex==my_dict[my_target]:
pass
# note: both index1 and index2 are not zero-based.
else:
# return [index, my_dict[my_target] ]
return [index+1, my_dict[my_target]+1 ]
# be careful: we need to plus '1' because they are 'not' zero-based!!