File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ # Create a empty hash table(seen) and store numbers as a key and their indices as a value
2+ # Iterate through the given array(nums)
3+ # For each numbers in given array, calculate complement (target - num)
4+ # If complement is in hash table(seen), return array of index of the currnet number and index of complement in hash table(seen)
5+ # If complement is not in has table(seen), store the current number in hash table(seen) and continue checking the numbers
6+ # The algorithm uses a single loop that goes through each element in nums exactly one time.
7+ # If the array contains n elements, the loop runs n times → O(n).
8+ # We use a hash table (seen) to store numbers we've already visited.
9+ # seen could contain up to n − 1 entries, so its size grows linearly with input size → O(n).
10+
11+
12+
13+ class Solution :
14+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
15+ seen = {}
16+ for i , num in enumerate (nums ):
17+ complement = target - num
18+ if complement in seen :
19+ return [seen [complement ], i ]
20+ seen [num ] = i
21+ return []
Original file line number Diff line number Diff line change 1+ /*
2+
3+
4+ // Create a empty hash table(seen) and store numbers as a key and their indices as a value
5+ // Iterate through the given array(nums)
6+ // For each numbers in given array, calculate complement (target - num)
7+ // If complement is in hash table(seen), return array of index of the currnet number and index of complement in hash table(seen)
8+ // If complement is not in has table(seen), store the current number in hash table(seen) and continue checking the numbers
9+ // The algorithm uses a single loop that goes through each element in nums exactly one time.
10+ // If the array contains n elements, the loop runs n times → O(n).
11+ We use a hash table (seen) to store numbers we've already visited.
12+ seen could contain up to n − 1 entries, so its size grows linearly with input size → O(n).
13+
14+
15+ */
16+
17+ function twoSum2 ( nums : number [ ] , target : number ) : number [ ] {
18+ const seen :{ [ key :number ] : number } = { } ;
19+ for ( let i = 0 ; i < nums . length ; i ++ ) {
20+ let complement = target - nums [ i ]
21+ if ( complement in seen ) {
22+ return [ seen [ complement ] , i ]
23+ }
24+ seen [ nums [ i ] ] = i
25+ }
26+ return [ ]
27+ } ;
You can’t perform that action at this time.
0 commit comments