LeetCode 力扣 1. 两数之和 哈希 暴力

本文详细解析了经典的“两数之和”问题,通过两种方法实现:暴力枚举和哈希查找。暴力方法虽然直观但效率较低,而哈希方法则通过预先计算并存储差值来快速匹配,显著提升了查找速度。

大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn


1. 两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

分析

暴力

直接枚举到底存不存在,简单粗暴,时间复杂度为 O ( n 2 ) O(n^2) O(n2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for(int i = 0; i< nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                if(target-nums[i] == nums[j]){
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }
}

哈希

先把差值complement记录下来,然后看看集合中有没有complement,有的话直接return数组,否则最后return空数组,注意,mapkey为数字,value为数字下标

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

提交结果

在这里插入图片描述


2020年9月22日更

大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn


### 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]。通过一次遍历数组,同时查询哈希表是否已经存在目标值的补数,从而避免了嵌套循环带来的额外时间开销。 ### 注意事项 - 哈希表的大小选取应为质数以减少冲突。 - 在实际应用中可能需要考虑更多边界条件,例如数组为空或只有一个元素的情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值