diff --git a/chapter_computational_complexity/space_complexity.md b/chapter_computational_complexity/space_complexity.md index 9b949d871..3dd7b5f0f 100755 --- a/chapter_computational_complexity/space_complexity.md +++ b/chapter_computational_complexity/space_complexity.md @@ -949,6 +949,13 @@ $$ === "C" ```c title="space_complexity.c" + /* 哈希表 */ + struct hashTable { + int key; + int val; + UT_hash_handle hh; // 基于 uthash.h 实现 + }; + /* 线性阶 */ void linear(int n) { // 长度为 n 的数组占用 O(n) 空间 @@ -968,7 +975,6 @@ $$ // 长度为 n 的哈希表占用 O(n) 空间 hashTable *h = NULL; - for (int i = 0; i < n; i++) { hashTable *tmp = malloc(sizeof(hashTable)); tmp->key = i; diff --git a/chapter_searching/replace_linear_by_hashing.md b/chapter_searching/replace_linear_by_hashing.md index aabaf7f1e..d4f86c177 100755 --- a/chapter_searching/replace_linear_by_hashing.md +++ b/chapter_searching/replace_linear_by_hashing.md @@ -322,6 +322,32 @@ comments: true === "C" ```c title="leetcode_two_sum.c" + /* 哈希表 */ + struct hashTable { + int key; + int val; + UT_hash_handle hh; // 基于 uthash.h 实现 + }; + + /* 哈希表查询 */ + hashTable *find(hashTable *h, int key) { + hashTable *tmp; + HASH_FIND_INT(h, &key, tmp); + return tmp; + } + + /* 哈希表元素插入 */ + void insert(hashTable *h, int key, int val) { + hashTable *t = find(h, key); + if (t == NULL) { + hashTable *tmp = malloc(sizeof(hashTable)); + tmp->key = key, tmp->val = val; + HASH_ADD_INT(h, key, tmp); + } else { + t->val = val; + } + } + /* 方法二:辅助哈希表 */ int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) { hashTable *hashtable = NULL;