Skip to content

Commit a8953ea

Browse files
Adding 1-Two-Sum.c
1 parent c8502c4 commit a8953ea

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

c/1-Two-Sum.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)