uthash.h
: github,也可以在gitee下载)注意在leetcode中使用uthash,head_table
在每个用例执行时都要初始化为NULL
,因为全局变量和静态变量的初始化只会执行一次。
c语言实现:
struct hash_table {
int key;
int value; // value
; /* makes this structure hashable */
UT_hash_handle hh};
// 必须要初始化为NULL,考虑到leetcode c语言实现执行多个用例时全局变量和静态变量只会初始化一次,
// 所以我们这里就不在这里初始化值,而是放到main()中,
// 防止以后从这里copy代码到leetcode中时用例不通过
static struct hash_table *head_table;
static void uthash_add(struct hash_table *add)
{
(head_table, key, add); // 这里的key不是变量,而是结构体成员名
HASH_ADD_INT}
static struct hash_table *uthash_find(int key)
{
struct hash_table *out;
(head_table, &key, out); // 这里的key是变量
HASH_FIND_INTreturn out;
}
static void uthash_delete(struct hash_table *del)
{
(head_table, del);
HASH_DEL}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
= NULL;
head_table struct hash_table *tmp;
for (int i = 0; i < numsSize; i++) {
= uthash_find(target - nums[i]);
tmp if (tmp) {
int *ret = malloc(sizeof(int) * 2);
[0] = tmp->value;
ret[1] = i;
ret*returnSize = 2;
return ret;
}
= malloc(sizeof(struct hash_table));
tmp ->key = nums[i];
tmp->value = i;
tmp(tmp);
uthash_add}
*returnSize = 0;
return NULL;
}
c语言实现:
struct hash_table {
int key;
int value; // value用不到,可以去掉
; /* makes this structure hashable */
UT_hash_handle hh};
// 只能放在函数里,放函数外用例失败
// struct hash_table *head_table = NULL;
bool containsDuplicate(int* nums, int numsSize) {
struct hash_table *head_table = NULL; // 只能放在函数里,放函数外用例失败
for (int i = 0; i < numsSize; i++) {
struct hash_table *tmp;
(head_table, &nums[i], tmp);
HASH_FIND_INTif (!tmp) {
= malloc(sizeof(struct hash_table));
tmp ->key = nums[i];
tmp(head_table, key, tmp);
HASH_ADD_INT} else {
return true;
}
}
return false;
}