题目来源
LeetCode:https://leetcode-cn.com/problems/two-sum
分析
具体思想可以参考这个题解的演示:https://leetcode-cn.com/problems/two-sum/solution/tu-jie-guan-fang-tui-jian-ti-jie-liang-s-02xs/,LeetCode中使用的哈希算法是通过uthash.h
这个文件实现的,该文件本来是个开源项目,目前已整合到gcc中,关于其使用请参考uthash的文档:https://troydhanson.github.io/uthash/userguide.html。
我的程序
struct numsHash{
int key; // 键值
int val; // 数据
UT_hash_handle hh;
};
struct numsHash* pNumsHashHead = NULL;
struct numsHash* Find_NumsHash(int targetKey) // 定义查询函数
{
struct numsHash *pReturn;
HASH_FIND_INT(pNumsHashHead, &targetKey, pReturn);
return pReturn;
}
void Add_NumsHash(int addKey, int addVal)
{
struct numsHash* pTarget = Find_NumsHash(addKey);
if(pTarget == NULL){
struct numsHash* pTempHash = malloc(sizeof(struct numsHash));
pTempHash->key = addKey;
pTempHash->val = addVal;
HASH_ADD_INT(pNumsHashHead, key, pTempHash);
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
pNumsHashHead = NULL;
for(int i = 0; i < numsSize; i++){
struct numsHash* pTempHash = Find_NumsHash(target - nums[i]);
if(pTempHash != NULL){
int* ret = malloc(sizeof(int) * 2);
ret[0] = pTempHash->val;
ret[1] = i;
*returnSize = 2;
return ret;
}
Add_NumsHash(nums[i], i);
}
*returnSize = 0;
return NULL;
}
运行结果
执行用时 | 内存消耗 |
---|---|
4ms | 7.6MB |