-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.py
More file actions
26 lines (22 loc) · 851 Bytes
/
two_sum.py
File metadata and controls
26 lines (22 loc) · 851 Bytes
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
# Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# create hash map to store previous values
prevMap = {}
# iterate through the list
for i, n in enumerate(nums):
# check if the difference is in the hash map
diff = target - n
if diff in prevMap:
# return current index and index of the difference as it totals the target
return [prevMap[diff], i]
# store the current value in the hash map and it's index
prevMap[n] = i
# {
# 3: 0
# 4: 1
# }
#
# [0, 1]
# O(n) Time
# O(n) Space