石神

V1

2023/03/08阅读:10主题:全栈蓝

【哈希表】两数之和

两数之和

本文只是节选公众号的中的一篇,我的公众号每日都会更新,欢迎参观 公众号算法每日一更
接下来会出现连续高能!

力扣链接:https://leetcode.cn/problems/two-sum/

题目描述:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [01] 。

提示:

  • 2 <= nums.length <= 104
  • 109 <= nums[i] <= 109
  • 109 <= target <= 109
  • 只会存在一个有效答案
  • 解法一:两层for

再啰嗦一回,如果是两个数,就是两层for,三个数就三次for,形成眼球记忆

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

inttwoSum(int* nums, int numsSize, int target, int* returnSize){
    for(int i = 0; i < numsSize; i++)
    {
        for(int j = i+1; j < numsSize; j++)
        {
            if(nums[i] + nums[j] == target)
            {
                nums[0] = i;
                nums[1] = j;
                *returnSize = 2;
                break;
            }
        }
    }
    return nums;
}
  • 解法二:哈希表

数组的哈希,类似于空间换时间

// 头文件 #include<tuhash.h>,
struct hashTable {
    int key;
    int val;
    UT_hash_handle hh;
};
// 以上是引入hash库

struct hashTablehashtable;
struct hashTable* find(int ikey) {
    struct hashTabletmp;
    HASH_FIND_INT(hashtable, &ikey, tmp);
    return tmp;
}

void insert(int ikey, int ival) {
    struct hashTableit = find(ikey);
    if (it == NULL) {
        struct hashTabletmp = malloc(sizeof(struct hashTable));
        tmp->key = ikey, tmp->val = ival;
        HASH_ADD_INT(hashtable, key, tmp);
    } else {
        it->val = ival;
    }
}

inttwoSum(int* nums, int numsSize, int target, int* returnSize) {
    hashtable = NULL;
    for (int i = 0; i < numsSize; i++) {
        struct hashTableit = find(target - nums[i]);
        if (it != NULL) {
            int* ret = malloc(sizeof(int) * 2);
            ret[0] = it->val, ret[1] = i;
            *returnSize = 2;
            return ret;
        }
        insert(nums[i], i);
    }
    *returnSize = 0;
    return NULL;
}

上面是官方解法,这里使用了hash库,可参考这篇文章:https://blog.csdn.net/qq_43094563/article/details/122352876

分类:

后端

标签:

后端

作者介绍

石神
V1