开源hash代码uthash的原理与用法
说明
需要包含头文件 #include “uthash.h”
参考leedcode1
添加链接描述
struct hashTable {
int key;
int value;
UT_hash_handle hh;
};
struct hashTable *hash;
struct hashTable *find(int key)
{
struct hashTable *tmp;
HASH_FIND_INT(hash, &key, tmp);
return tmp;
}
void insert(int key, int value)
{
struct hashTable *it = find(key);
if (it == NULL) {
struct hashTable *tmp = (struct hashTable *)malloc(sizeof(struct hashTable));
tmp->key = key;
tmp->value = value;
HASH_ADD_INT(hash, key, tmp);
} else {
it->value = value;
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
hash = NULL;
for (int i = 0; i < numsSize; i++) {
struct hashTable *tmp = find(target - nums[i]);
if (tmp != NULL) {
int *ret = (int *)malloc(sizeof(int) * 2);
ret[0] = tmp->value;
ret[1] = i;
*returnSize = 2;
return ret;
}
insert(nums[i], i);
}
*returnSize = 0;
return NULL;
}