哈希表·uthash的实战应用及总结 实战应用幸运的是在leetcode中系统为我们默认被导入了 uthash.h。因此我们可以直接进行使用。以最经典的1. 两数之和进行展示。简述算法思路目标是找出nums[i] nums[j] target。将公式移向可得nums[j] target - nums[i]。因此我们在遍历当前的数nums[i]时搜寻是否有历史的target - nums[i]。为了给后续遍历提供查找的遍历注意将nums[i]存入哈希表即可。struct MyHashNode { int key; int value; // 必须定义名为 hh 的 UT_hash_handle UT_hash_handle hh; }; // 增 会修改原hashtable的结构 void hash_insert(struct MyHashNode **hashTable, struct MyHashNode *node) { HASH_ADD_INT(*hashTable, key, node); } // 查 struct MyHashNode *hash_find(struct MyHashNode *hashTable, int key) { struct MyHashNode *node NULL; HASH_FIND_INT(hashTable, key, node); return node; } /** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ struct MyHashNode *manager NULL; // 哈希表快速查找法。 for (int i 0; i numsSize; i 1) { int diff target - nums[i]; struct MyHashNode* node hash_find(manager, diff); if (node ! NULL) { *returnSize 2; int *ret (int*) malloc(sizeof(int) * 2); ret[0] node-value; ret[1] i; return ret; } else { node (struct MyHashNode*)malloc(sizeof(struct MyHashNode)); node-key nums[i]; node-value i; hash_insert(manager, node); } } *returnSize 0; return NULL; }小结uthash是一个非常轻量级的库。该库的使用非常简单无需格外的静态库或动态库仅需导入目标的头文件即可。这种配置方式虽然简单但是使用操作却需要用到大量的宏函数。在使用宏函数时不像使用普通函数一样自由和遍历且通常难以debug。并且还需要根据指定的方式定义哈希节点如要求必须存在UT_hash_handle hh;使用HASH_ADD_INT()时第二多个参数必须与哈希节点中作为键的变量的字面量一致等等。那么是否还建议学习使用uthash呢答案是建议。首先在C语言中使用普通数组作为哈希表时限制非常大很多时候并不能满足我们的需求。如不能对数组越界访问若需要的键过大则很占用空间无法做到使用浮点数字符串等作为下标等等。其次使用这类三方库可以锻炼我们对指针的使用对宏函数的使用对结构体的使用。这些都是我们编程中的基本功只有打好基本功才可以帮助我们学习更多相关的新知识。