File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * 1. O(n^2) brute force
5+ * 2. hash table
6+ */
7+
8+ /**
9+ * @description brainstorming 1 solve
10+ * time complexity: O(n^2)
11+ * space complexity: O(n)
12+ */
13+ var twoSum = function ( nums , target ) {
14+ for ( let i = 0 ; i < nums . length ; i ++ ) {
15+ for ( let j = i + 1 ; j < nums . length ; j ++ ) {
16+ if ( nums [ i ] + nums [ j ] === target ) return [ i , j ] ;
17+ }
18+ }
19+ } ;
20+
21+ /**
22+ * @description brainstorming 2 solve
23+ * time complexity: O(n^2)
24+ * space complexity: O(n)
25+ */
26+ var twoSum = function ( nums , target ) {
27+ const map = new Map ( ) ;
28+
29+ nums . forEach ( ( num , index ) => {
30+ if ( ! map . get ( num ) ) return map . set ( num , [ index ] ) ;
31+
32+ map . set ( num , map . get ( num ) . concat ( index ) ) ;
33+ } ) ;
34+
35+ for ( let i = 0 ; i < nums . length ; i ++ ) {
36+ const rest = target - nums [ i ] ;
37+
38+ if ( ! map . get ( rest ) ) continue ;
39+
40+ const indexList = map . get ( rest ) ;
41+ for ( let j = 0 ; j < indexList . length ; j ++ ) {
42+ if ( i === indexList [ j ] ) continue ;
43+
44+ return [ i , indexList [ j ] ] ;
45+ }
46+ }
47+ } ;
You can’t perform that action at this time.
0 commit comments