-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwosum.c
47 lines (43 loc) · 1.12 KB
/
twosum.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
44
45
46
47
/**
C solution in O(n) time, using open addressing hash table.
*/
#define SIZE 50000
int hash(int key) {
int r = key % SIZE;
return r < 0 ? r + SIZE : r;
}
void insert(int *keys, int *values, int key, int value) {
int index = hash(key);
while (values[index]) {
index = (index + 1) % SIZE;
}
keys[index] = key;
values[index] = value;
}
int search(int *keys, int *values, int key) {
int index = hash(key);
while (values[index]) {
if (keys[index] == key) {
return values[index];
}
index = (index + 1) % SIZE;
}
return 0;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = 2;
int keys[SIZE];
int values[SIZE] = {0};
for (int i = 0; i < numsSize; i++) {
int complements = target - nums[i];
int value = search(keys, values, complements);
if (value) {
int *indices = (int *) malloc(sizeof(int) * 2);
indices[0] = value - 1;
indices[1] = i;
return indices;
}
insert(keys, values, nums[i], i + 1);
}
return NULL;
}