Skip to content

Instantly share code, notes, and snippets.

@jj11hh
Created May 22, 2020 15:51
Show Gist options
  • Select an option

  • Save jj11hh/169fb81e90bedef06a7e7c8b57a8d01e to your computer and use it in GitHub Desktop.

Select an option

Save jj11hh/169fb81e90bedef06a7e7c8b57a8d01e to your computer and use it in GitHub Desktop.
hash table and fast two sum in C
typedef struct _node {
int k;
int v;
struct _node * next;
} node;
static int hash (int x, int m){
return ((x ^ 0x3FB15C87) & ~0x80000000) % m;
}
void hashins(node **T, int m, int k, int v){
int h = hash(k, m);
node *p;
node *n = malloc(sizeof(node));
n->k = k;
n->v = v;
n->next = NULL;
if (T[h] == NULL){
T[h] = n;
}
else {
p = T[h];
while (1){
if (p->k == k){
p->v = v;
free(n);
return;
}
else if (p->next == NULL){
p->next = n;
return;
}
p = p->next;
}
}
}
int hashsrh(node **T, int m, int k, int *v){
int h = hash(k, m);
node *p = T[h];
if (!p) return -1; // NFOUND
while (p){
if (p->k == k){
*v = p->v;
return 0;
}
p = p->next;
}
return -1; //NFOUND
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
node **T = calloc(numsSize, sizeof(node *));
memset(T, 0, numsSize * sizeof(node*));
int m = numsSize;
*returnSize = 2;
int *r = malloc(2 * sizeof(int));
for (int i = 0; i < numsSize; i ++){
hashins(T, m, target - nums[i], i);
}
for (int i = 0; i < numsSize; i ++){
int j;
if (hashsrh(T, m, nums[i], &j) == 0 && i != j){
r[0] = i; r[1] = j;
return r;
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment