哈希表 1.两数之和

用hashmap来解,先判断是否为空。对数组每一个进行遍历,用 target - nums[i],得temp,只需循环判断一个数,从0开始,但此时并不急着将数放入map,可能会存在不用相加就得到target的情况。所有判断完之后,再将遍历过的加入map。每一次遍历都创建一个新的哈希表,防止出现意外情况

public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    if(nums == null || nums.length == 0){
        return res;
    }
    Map<Integer, Integer> map = new HashMap<>();
    for(int i = 0; i < nums.length; i++){
        int temp = target - nums[i];   // 遍历当前元素,并在map中寻找是否有匹配的key
        if(map.containsKey(temp)){
            res[1] = i;
            res[0] = map.get(temp);
            break;
        }
        map.put(nums[i], i);    // 如果没找到匹配对,就把访问过的元素和下标加入到map中
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
哈希表可以用来解决两数之和的问题。在C语言中,我们可以使用哈希表来记录每个元素的值和对应的索引。然后遍历数组,对于每个元素,我们可以检查哈希表中是否存在目标值减去当前元素的差值,如果存在,则找到了符合条件的两个数。 下面是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct { int value; int index; } HashNode; int* twoSum(int* nums, int numsSize, int target, int* returnSize) { HashNode* hashTable = (HashNode*)malloc(numsSize * sizeof(HashNode)); int* result = (int*)malloc(2 * sizeof(int)); for (int i = 0; i < numsSize; i++) { hashTable[i].value = -1; hashTable[i].index = -1; } for (int i = 0; i < numsSize; i++) { int complement = target - nums[i]; int hashIndex = abs(complement) % numsSize; while (hashTable[hashIndex].value != -1 && hashTable[hashIndex].value != complement) { hashIndex = (hashIndex + 1) % numsSize; } if (hashTable[hashIndex].value == complement) { result[0] = hashTable[hashIndex].index; result[1] = i; *returnSize = 2; break; } hashTable[hashIndex].value = nums[i]; hashTable[hashIndex].index = i; } free(hashTable); return result; } int main() { int nums[] = {2, 7, 11, 15}; int target = 9; int returnSize; int* result = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize); printf("Indices: %d, %d\n", result[0], result[1]); free(result); return 0; } ``` 这里定义了一个哈希表结构 `HashNode`,包含值和索引两个字段。`twoSum` 函数接受一个整数数组 `nums`、数组长度 `numsSize`、目标值 `target` 和指向返回结果大小的指针 `returnSize`。函数使用哈希表记录每个元素的值和索引,然后遍历数组进行查找,找到符合条件的两个数后,将它们的索引保存在 `result` 数组中,并通过 `returnSize` 返回结果大小。 在主函数中,我们使用示例数组 `{2, 7, 11, 15}`,目标值为 `9`。执行 `twoSum` 函数后,会得到符合条件的两个数在数组中的索引,并打印输出。 希望能帮到你!如有疑问,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值