哈希表

点击这里查看配套的教学视频

点击跳转到算法课程所有目录

1 uthash

注意在leetcode中使用uthash,head_table在每个用例执行时都要初始化为NULL,因为全局变量和静态变量的初始化只会执行一次。

2 leetcode 1. 两数之和

c语言实现:

struct hash_table {
    int key;
    int value; // value
    UT_hash_handle hh; /* makes this structure hashable */
};

// 必须要初始化为NULL,考虑到leetcode c语言实现执行多个用例时全局变量和静态变量只会初始化一次,
// 所以我们这里就不在这里初始化值,而是放到main()中,
// 防止以后从这里copy代码到leetcode中时用例不通过
static struct hash_table *head_table;

static void uthash_add(struct hash_table *add)
{
    HASH_ADD_INT(head_table, key, add); // 这里的key不是变量,而是结构体成员名
}

static struct hash_table *uthash_find(int key)
{
    struct hash_table *out;

    HASH_FIND_INT(head_table, &key, out); // 这里的key是变量
    return out;
}

static void uthash_delete(struct hash_table *del)
{
    HASH_DEL(head_table, del);
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    head_table = NULL;
    struct hash_table *tmp;
    for (int i = 0; i < numsSize; i++) {
        tmp = uthash_find(target - nums[i]);
        if (tmp) {
            int *ret = malloc(sizeof(int) * 2);
            ret[0] = tmp->value;
            ret[1] = i;
            *returnSize = 2;
            return ret;
        }
        tmp = malloc(sizeof(struct hash_table));
        tmp->key = nums[i];
        tmp->value = i;
        uthash_add(tmp);
    }
    *returnSize = 0;
    return NULL;
}

3 leetcode 496. 下一个更大元素 I

点击这里查看“单调栈 + 哈希表”的解法

4 leetcode 217. 存在重复元素

c语言实现:

struct hash_table {
    int key;
    int value;  // value用不到,可以去掉
    UT_hash_handle hh; /* makes this structure hashable */
};

// 只能放在函数里,放函数外用例失败
// 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;
        HASH_FIND_INT(head_table, &nums[i], tmp);
        if (!tmp) {
            tmp = malloc(sizeof(struct hash_table));
            tmp->key = nums[i];
            HASH_ADD_INT(head_table, key, tmp);
        } else {
            return true;
        }
    }
    return false;
}