這裏是引用
typedef struct Node_Class Node;
typedef struct HashMap_Class HashMap;
struct Node_Class {
int key;
int value;
struct Node_Class *next;
};
struct HashMap_Class
{
int threshold;
struct Node_Class** table;
};
void HashMap_Init(HashMap* map,int initialCapacity) {
int threshold = 1;
while (threshold < initialCapacity)
threshold <<= 1;
map->threshold = threshold;
Node** table = malloc(sizeof(Node)*threshold);
memset(table, 0, sizeof(Node) * threshold);
map->table = table;
}
int HashMap_HashCode(HashMap* map, int key) {
return key;
}
void HashMap_Put(HashMap* map,int key,int value) {
Node *p;
Node *tail;
unsigned int hash = (unsigned int)HashMap_HashCode(map, key);
hash= hash ^ (hash >> 16);
hash=hash&(map->threshold - 1);
p = map->table[hash];
if (p == NULL) {
Node* node = malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
map->table[hash] = node;
}else {
while (p != NULL) {
if (p->key == key) {
p->value = value;
break;
}
tail = p;
p = p->next;
if (p == NULL) {
Node* node = malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
tail->next = node;
}
}
}
}
Node* HashMap_Get(HashMap* map, int key) {
Node *p;
unsigned int hash = (unsigned int)HashMap_HashCode(map, key);
hash = hash ^ (hash >> 16);
hash = hash & (map->threshold - 1);
p = map->table[hash];
if (p == NULL) {
return NULL;
}
else {
while (p != NULL) {
if (p->key == key) {
return p;
break;
}
p = p->next;
if (p == NULL) {
return NULL;
}
}
}
return NULL;
}
bool HashMap_Contains(HashMap* map, int key) {
if (HashMap_Get(map, key) != NULL) {
return true;
}
else {
return false;
}
}
void HashMap_Free(HashMap* map) {
for (int i = 0; i < map->threshold; i++) {
Node *e***y = map->table[i];
while (e***y != NULL) {
Node *temp = e***y ;
e***y = e***y ->next;
free(temp);
}
}
free(map->table);
free(map);
}
int* twoSum(int* nums, int numsSize, int target)
{
if (numsSize < 2) return NULL;
int *res = (int *)malloc(sizeof(int) * 2);
int initialCapacity = (int)((float)numsSize/ 0.75F + 1.0F);
HashMap* map = malloc(sizeof(HashMap));
HashMap_Init(map,initialCapacity);
for (int i = 0; i < numsSize; i++) {
if (!HashMap_Contains(map,target - nums[i])) {
HashMap_Put(map,nums[i], i);
}
else {
res[0] = HashMap_Get(map,target - nums[i])->value;
res[1] = i;
break;
}
}
HashMap_Free(map);
return res;
}