-
Notifications
You must be signed in to change notification settings - Fork 29
/
0001-Two-Sum.py
41 lines (31 loc) · 1.02 KB
/
0001-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
39
40
41
'''
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
'''
from typing import List
# Using Hash Tables
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i in range(len(nums)):
temp = target-nums[i]
if temp in dict:
return [dict[temp], i]
dict.update({nums[i] : i})
# Using Hash Tables (New)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for index, num in enumerate(nums):
if target - num in d.keys():
return [d[target - num], index]
else:
d[num] = index
# Check Custom Input
s = Solution()
answer = s.twoSum([3,2,1,5], 8) # [0,3]
print(answer)