两数之和哈希方法

例题解析

作者:力扣官方题解 链接:力扣 来源:力扣(LeetCode)

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

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

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

示例 1:

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

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

提示:

  • 2 <= nums.length <= 104

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

  • 只会存在一个有效答案

进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?

力扣官方解答:

查找表法:在遍历的同时,记录一些信息,以省去一层循环。

01234
nums63821target

此时找到6,6不在map中,存入。

mapkey6
value0

此时找到3,target-nums[i]=5,5不在map中,将其存入。

mapkey65
value01

此时找到8,target-num[i]=0,0不在map中,存入。

mapkey658
value012

此时找到2,target-num[i]=6,6在map中。6为我们要寻找的。

mapkey658
value012

java解法

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
        for(int i = 0;i<nums.length ;i++){
            if (hashMap.containsKey(target-nums[i])){
                return new int [] { hashMap.get(target - nums[i]), i};
            }
            hashMap.put(nums[i],i);
        }
        return new int[0];
    }
}

c++解法

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};

c语言解法

struct hashTable {
    int key;
    int val;
    UT_hash_handle hh;
};
​
struct hashTable* hashtable;
​
struct hashTable* find(int ikey) {
    struct hashTable* tmp;
    HASH_FIND_INT(hashtable, &ikey, tmp);
    return tmp;
}
​
void insert(int ikey, int ival) {
    struct hashTable* it = find(ikey);
    if (it == NULL) {
        struct hashTable* tmp = malloc(sizeof(struct hashTable));
        tmp->key = ikey, tmp->val = ival;
        HASH_ADD_INT(hashtable, key, tmp);
    } else {
        it->val = ival;
    }
}
​
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    hashtable = NULL;
    for (int i = 0; i < numsSize; i++) {
        struct hashTable* it = 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;
}

UT_hash_handle hh; 是一个特殊的成员变量,它是来自于 uthash 库的一部分,用于管理哈希表的内部结构。将 hh 成员变量包含在结构体中是为了支持使用 uthash 宏操作哈希表。

uthash 是一个在 C 语言中实现的高效哈希表的库,它提供了一组宏来操作哈希表。这些宏通过让用户在结构体中包含特定的成员变量来实现。其中 UT_hash_handle 是一个表示哈希表句柄的特殊结构体成员。UT_hash_handle hh是一个哈希表句柄(hash table handle)是一种用于管理哈希表的数据结构或指针。它允许用户通过句柄访问和操作哈希表的不同部分,例如插入、删除、查找等操作。

### C语言实现力扣两数问题的哈希表解决方案 以下是使用C语言实现的LeetCode两数(Two Sum)问题的哈希表解决方案。此方法通过构建哈希表来存储数组中的元素及其索引,从而将时间复杂度降低到O(n)。 #### 哈希表结构定义 首先需要定义一个简单的哈希表节点结构以及相关的操作函数。这里采用链地址法解决哈希冲突。 ```c #include <stdio.h> #include <stdlib.h> #define HASH_SIZE 1009 // 选择一个质数作为哈希表大小 typedef struct Node { int key; // 数组中的值 int value; // 数组中的索引 struct Node* next; } Node; typedef struct { Node* buckets[HASH_SIZE]; } HashTable; // 初始化哈希表 void initHashTable(HashTable* ht) { for (int i = 0; i < HASH_SIZE; ++i) { ht->buckets[i] = NULL; } } // 计算哈希值 int hashFunction(int key) { return abs(key) % HASH_SIZE; } // 插入键值对到哈希表中 void insert(HashTable* ht, int key, int value) { int index = hashFunction(key); Node* newNode = (Node*)malloc(sizeof(Node)); newNode->key = key; newNode->value = value; newNode->next = ht->buckets[index]; ht->buckets[index] = newNode; } // 查找键对应的值 int find(HashTable* ht, int key) { int index = hashFunction(key); Node* current = ht->buckets[index]; while (current != NULL) { if (current->key == key) { return current->value; } current = current->next; } return -1; // 如果未找到返回-1 } ``` #### 主函数实现 接下来是主函数部分,它会遍历输入数组并利用哈希表查找目标值与当前元素的差值是否存在。 ```c int* twoSum(int* nums, int numsSize, int target, int* returnSize) { HashTable ht; initHashTable(&ht); int* result = (int*)malloc(2 * sizeof(int)); *returnSize = 2; for (int i = 0; i < numsSize; ++i) { int complement = target - nums[i]; int index = find(&ht, complement); if (index != -1 && index != i) { result[0] = index; result[1] = i; return result; } insert(&ht, nums[i], i); } *returnSize = 0; return NULL; } int main() { int nums[] = {2, 7, 11, 15}; int target = 9; int numsSize = sizeof(nums) / sizeof(nums[0]); int returnSize; int* result = twoSum(nums, numsSize, target, &returnSize); if (returnSize == 2) { printf("Indices: %d, %d\n", result[0], result[1]); } else { printf("No solution found.\n"); } free(result); return 0; } ``` 上述代码实现了两数问题的哈希表解决方案[^1]。通过一次遍历数组,同时查询哈希表是否已经存在目标值的补数,从而避免了嵌套循环带来的额外时间开销。 ### 注意事项 - 哈希表的大小选取应为质数以减少冲突。 - 在实际应用中可能需要考虑更多边界条件,例如数组为空或只有一个元素的情况。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值