File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+ from typing import Dict
3
+
4
+
5
+ class Solution :
6
+ # Time: O(n)
7
+ # Space: O(n)
8
+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
9
+ # 1. Make a map {target - num : index of num} with the list nums.
10
+ # Time: O(n)
11
+ # Space: O(n)
12
+ mapOfSubtractedValueToIndex : Dict [int , int ] = ({
13
+ target - num : index for index , num in enumerate (nums )
14
+ })
15
+
16
+ # 2. ForEach num in nums, get value from the map.
17
+ # Time: O(n)
18
+ # Space: O(n)
19
+ result : List [int ] = None
20
+ for indexOfNum , num in enumerate (nums ):
21
+ try :
22
+ indexOfSubtractedValue = mapOfSubtractedValueToIndex [num ]
23
+ if indexOfSubtractedValue == indexOfNum :
24
+ continue
25
+ # 3. Return the index of num in nums and the value from the map.
26
+ return [indexOfNum , indexOfSubtractedValue ]
27
+ except KeyError :
28
+ continue
You can’t perform that action at this time.
0 commit comments