两数之和

发布时间 2023-06-03 09:17:25作者: 颖风船

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


 

 

使用哈希表实现:

1、遍历数组中每个数,判断目标值和当前差值是否在哈希表

2、如果存在,则返回差值对应的下标和当前值的下标

3、如果不存在,则将当前值和下标存入哈希表中,等待下次查询

使用C++实现:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hash; // 哈希表存储每个出现过的值以及其对应的下标

        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i]; // 计算目标值与当前值的差值
            if (hash.count(complement)) { // 如果存在差值,则直接返回差值对应的下标和当前值的下标
                return {hash[complement], i};
            }
            hash[nums[i]] = i; // 将当前值及其下标存入哈希表中,等待下次查询
        }
        return {}; // 没有符合条件的数对,返回空数组
    }
};

 

 

使用C语言实现

typedef struct {
    int key;    // 存储数字
    int val;    // 存储下标
    UT_hash_handle hh; 
} hashTable;    // 定义哈希表结构体类型

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    hashTable* hash = NULL;   // 声明一个哈希表
    int* res = (int*)malloc(sizeof(int) * 2); // 存储返回结果
    *returnSize = 0;    // 初始化返回结果的长度为 0

    for (int i = 0; i < numsSize; i++) {
        int complement = target - nums[i]; // 计算目标值与当前值的差值
        hashTable* tmp;
        HASH_FIND_INT(hash, &complement, tmp); // 查找哈希表中是否有差值所对应的数

        if(tmp != NULL)
     { res[0] = tmp->val; // 如果存在,则直接返回差值对应的下标和当前值的下标 res[1] = i; *returnSize = 2; return res; }
hashTable* element = (hashTable*)malloc(sizeof(hashTable)); // 如果不存在,则将当前值及其下标存入哈希表中 element->key = nums[i]; element->val = i; HASH_ADD_INT(hash, key, element); } return res; // 如果没有符合条件的数对,则返回空数组 }