add Two Sum task
This commit is contained in:
48
Two Sum/solution.c
Normal file
48
Two Sum/solution.c
Normal file
@@ -0,0 +1,48 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user