哈希表|1.两数之和

力扣题目链接


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

// leetcode 支持 ut_hash 函式庫

 typedef struct {
     int key;
     int value;
     UT_hash_handle hh; // make this structure hashable
 } map;

map* hashMap = NULL;

 void hashMapAdd(int key, int value){
     map* s;
     // key already in the hash?
     HASH_FIND_INT(hashMap, &key, s);
     if(s == NULL){
         s = (map*)malloc(sizeof(map));
         s -> key = key;
         HASH_ADD_INT(hashMap, key, s);
     }
     s -> value = value;
 }

map* hashMapFind(int key){
     map* s;
     // *s: output pointer
     HASH_FIND_INT(hashMap, &key, s);   
     return s;
 }

 void hashMapCleanup(){
     map* cur, *tmp;
     HASH_ITER(hh, hashMap, cur, tmp){
         HASH_DEL(hashMap, cur);
         free(cur);
     }
 }

 void hashPrint(){
     map* s;
     for(s = hashMap; s != NULL; s=(map*)(s -> hh.next)){
         printf("key %d, value %d\n", s -> key, s -> value);
     }
 }

 
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int i, *ans;
    // hash find result
    map* hashMapRes; 
    hashMap = NULL;
    ans = malloc(sizeof(int) * 2);

    for(i = 0; i < numsSize; i++){
        // key 代表 nums[i] 的值,value 代表所在 index;
        hashMapAdd(nums[i], i);
    }

    hashPrint();

    for(i = 0; i < numsSize; i++){
        hashMapRes = hashMapFind(target - nums[i]);
        if(hashMapRes && hashMapRes -> value != i){
            ans[0] = i;
            ans[1] = hashMapRes -> value ;
            *returnSize = 2;
            return ans;
        }
    }
    
    hashMapCleanup();
    return NULL;
}

这题你有没有和我一样,一看到这种哈希解法就不想看了?

好吧,我就是,所以我选择了用暴力,还是的菜鸟,能做出就知足了。

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    
    int n = numsSize;

    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++) {
            if(nums[i] + nums[j] == target) {
                * returnSize = 2;
                int* ans = (int*)malloc(sizeof(int)*2);
                ans[0] = i; 
                ans[1] = j;
                return ans;
            }
        }
    } 
    *returnSize = 0;
    return NULL;
}

 这应该好理解吧,然后下面就是我自己独立敲的,到最后也忘记了咋存储呜呜呜

一、出错点

1.不太理解哈希表解法,换用暴力

2.最后存储下标时忘记该怎么存储

二、理解后的思路

暴力很好理解,就是一个一个遍历相加。

有符合的sum就标记起来

最后输出下标

代码随想录 (programmercarl.com)

这里有怎样用哈希表的思路,但是我还不太清楚

三、总结 

当然还是多刷题,独立敲代码啦!

然后对于哈希表自己需要再好好看看,慢慢要学会灵活使用它了~

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值