File tree Expand file tree Collapse file tree 1 file changed +36
-7
lines changed
solution/0000-0099/0001.Two Sum Expand file tree Collapse file tree 1 file changed +36
-7
lines changed Original file line number Diff line number Diff line change
1
+ #include <stdlib.h>
2
+
1
3
int * twoSum (int * nums , int numsSize , int target , int * returnSize ) {
2
- for (int i = 0 ; i < numsSize ; i ++ ) {
3
- for (int j = i + 1 ; j < numsSize ; j ++ ) {
4
- if (nums [i ] + nums [j ] == target ) {
5
- int * result = (int * ) malloc (2 * sizeof (int ));
6
- result [0 ] = i ;
7
- result [1 ] = j ;
4
+ int capacity = 1 ;
5
+ while (capacity < numsSize * 2 ) capacity <<= 1 ;
6
+ int * keys = malloc (capacity * sizeof (int ));
7
+ int * vals = malloc (capacity * sizeof (int ));
8
+ char * used = calloc (capacity , sizeof (char ));
9
+ if (!keys || !vals || !used ) {
10
+ free (keys );
11
+ free (vals );
12
+ free (used );
13
+ * returnSize = 0 ;
14
+ return NULL ;
15
+ }
16
+ for (int i = 0 ; i < numsSize ; ++ i ) {
17
+ int x = nums [i ];
18
+ int y = target - x ;
19
+ unsigned int h = (unsigned int ) y & (capacity - 1 );
20
+ while (used [h ]) {
21
+ if (keys [h ] == y ) {
22
+ int * res = malloc (2 * sizeof (int ));
23
+ res [0 ] = vals [h ];
24
+ res [1 ] = i ;
8
25
* returnSize = 2 ;
9
- return result ;
26
+ free (keys );
27
+ free (vals );
28
+ free (used );
29
+ return res ;
10
30
}
31
+ h = (h + 1 ) & (capacity - 1 );
11
32
}
33
+ unsigned int h2 = (unsigned int ) x & (capacity - 1 );
34
+ while (used [h2 ]) h2 = (h2 + 1 ) & (capacity - 1 );
35
+ used [h2 ] = 1 ;
36
+ keys [h2 ] = x ;
37
+ vals [h2 ] = i ;
12
38
}
13
39
* returnSize = 0 ;
40
+ free (keys );
41
+ free (vals );
42
+ free (used );
14
43
return NULL ;
15
44
}
You can’t perform that action at this time.
0 commit comments