File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 1. Two Sum
3+
4+ use a hash map to store the numbers and their indices.
5+ iterate through the list and check if the complement of the current number (target - nums[i]) is in the hash map.
6+
7+ (assume that each input would have exactly one solution)
8+ - if it is a pairNum, return the indices of the two numbers.
9+ - if it is not, add the current number and its index to the hash map.
10+
11+
12+ ## Time and Space Complexity
13+
14+ ```
15+ TC: O(n)
16+ SC: O(n)
17+ ```
18+
19+ #### TC is O(n):
20+ - iterating through the list just once to find the two numbers. = O(n)
21+
22+ #### SC is O(n):
23+ - using a hash map to store the numbers and their indices. = O(n)
24+ '''
25+
26+ class Solution :
27+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
28+ map = {}
29+ for i in range (len (nums )):
30+ pairNum = target - nums [i ]
31+ if pairNum in map :
32+ return [map .get (pairNum ), i ]
33+ map [nums [i ]] = i
You can’t perform that action at this time.
0 commit comments