File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Time: O(n)
3+ Space: O(n)
4+ */
5+
6+ typedef struct {
7+ int key ; // key of hash_table
8+ int val ;
9+
10+ UT_hash_handle hh ; // Makes this structure hashable
11+ } hash_table ;
12+
13+ hash_table * hash = NULL , * elem , * tmp ;
14+
15+ int * twoSum (int * nums , int numsSize , int target , int * returnSize ){
16+ int * res = calloc ((* returnSize = 2 ), sizeof (int ));
17+
18+ for (int i = 0 ; i < numsSize ; ++ i ){
19+ int k = target - nums [i ];
20+
21+ HASH_FIND_INT (hash , & k , elem ); // Look for the item in hash table
22+
23+ if (elem ) {
24+ res [0 ] = elem -> val ;
25+ res [1 ] = i ;
26+ break ;
27+ }
28+ else {
29+ elem = malloc (sizeof (hash_table ));
30+ elem -> key = nums [i ]; // array element as key of hash table
31+ elem -> val = i ; // index of an element as value of hash table
32+
33+ HASH_ADD_INT (hash , key , elem ); // Add item to hash table
34+ }
35+ }
36+
37+ // Free up the hash table
38+ HASH_ITER (hh , hash , elem , tmp ) {
39+ HASH_DEL (hash , elem ); free (elem );
40+ }
41+
42+ return res ;
43+ }
You can’t perform that action at this time.
0 commit comments