49 lines
1.0 KiB
C
49 lines
1.0 KiB
C
#include <stdlib.h>
|
|
|
|
typedef struct {
|
|
int key;
|
|
int value;
|
|
int used;
|
|
} Entry;
|
|
|
|
int hash(int key, int size) {
|
|
return (key % size + size) % size;
|
|
}
|
|
|
|
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
|
|
|
|
int tableSize = numsSize * 2;
|
|
Entry* table = calloc(tableSize, sizeof(Entry));
|
|
|
|
int* res = malloc(sizeof(int) * 2);
|
|
*returnSize = 2;
|
|
|
|
for (int i = 0; i < numsSize; i++) {
|
|
int complement = target - nums[i];
|
|
int h = hash(complement, tableSize);
|
|
|
|
while (table[h].used) {
|
|
if (table[h].key == complement) {
|
|
res[0] = i;
|
|
res[1] = table[h].value;
|
|
free(table);
|
|
return res;
|
|
}
|
|
h = (h + 1) % tableSize;
|
|
}
|
|
|
|
h = hash(nums[i], tableSize);
|
|
while (table[h].used) {
|
|
h = (h + 1) % tableSize;
|
|
}
|
|
|
|
table[h].used = 1;
|
|
table[h].key = nums[i];
|
|
table[h].value = i;
|
|
}
|
|
|
|
free(table);
|
|
return res;
|
|
}
|
|
|