- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
45 lines (36 loc) · 1.01 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// one pass hash table solution with uthash
typedefstruct {
intvalue;
intindex;
UT_hash_handlehh;
} hashTable;
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int*twoSum(int*nums, intnumsSize, inttarget, int*returnSize){
if(nums==NULL||numsSize==0) {
*returnSize=0;
returnNULL;
}
*returnSize=2;
int*result= (int*)malloc(*returnSize*sizeof(int));
hashTable*hash=NULL, *elem, *temp;
for(inti=0; i<numsSize; i++) {
intlookupKey=nums[i];
intcomplement=target-lookupKey;
HASH_FIND_INT(hash, &complement, elem);
if(elem) {
result[0] =elem->index;
result[1] =i;
break;
}
elem=malloc(sizeof(hashTable));
elem->value=nums[i];
elem->index=i;
HASH_ADD_INT(hash, value, elem);
}
HASH_ITER(hh, hash, elem, temp) {
free(elem);
}
returnresult;
}