Skip to content

Commit f007c0f

Browse files
committed
O(n) time and O(n) space using Hashtable.
1 parent 9aea93e commit f007c0f

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

1. Two Sum/1. Two Sum.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1+
"""
2+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
3+
4+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
5+
6+
Example:
7+
8+
Given nums = [2, 7, 11, 15], target = 9,
9+
10+
Because nums[0] + nums[1] = 2 + 7 = 9,
11+
return [0, 1].
12+
"""
113
class Solution:
214
def twoSum(self, nums: List[int], target: int) -> List[int]:
3-
hmap={}
4-
for index,val in enumerate(nums):
5-
temp = target - val
15+
hmap = {}
16+
for i,v in enumerate(nums):
17+
temp = target - v
618
if temp in hmap.keys():
7-
return (hmap[temp],index)
8-
hmap[val] = index
19+
return [hmap[temp],i]
20+
hmap[v] = i

0 commit comments

Comments
 (0)