LeetCode---1.两数之和

两数之和

https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:

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

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

一、暴力法,执行结果下图:
在这里插入图片描述

int *twoSum(int *nums, int numsSize, int target, int *returnSize)
{
    int *result = (int *)malloc(sizeof(int) * 2);
    for (int i = 0; i < numsSize - 1; i++)
    {
        for (int j = i + 1; j < numsSize; j++)
        {
            if (nums[i] + nums[j] == target)
            {
                result[0] = i;
                result[1] = j;
                *returnSize = 2;
                return result;
            }
        }
    }
    return result;
}

二、数组散列法
先看执行结果: (30倍!!!)
在这里插入图片描述
没必要使用C语言实现hash操作,直接使用数组进行散列, 即将 nums 中的元素值当下标,nums的下标当值存储在 hash 数组中 : hash[ nums[i] ] = 1;

  1. 首先初始化 hash[2000], 初始值设为 -1 ,
    遍历数组, 查看 target - nums[i] 为下标 的 hash 数组元素值 (hash[ target - nums[i] ]) 是否为 - 1;
  2. 若为 -1 ,将 下标 i 存放在 hash数组的 nums[i] 位置上, hash[ nums[i] ] = i;
  3. 若不为 -1 ,即存在 相加为 target 的元素,两个元素的下标为 hash[ target - nums[i]] , i;

注意: 测试用例中存在负数,在散列时会访问越界,故使用求余法,将负数散列到数组尾部 : hash[(nums[i] + MAX_SIZE) % MAX_SIZE] = i; 查找时也要如此;
就是负数放到后面

希望图能看懂
在这里插入图片描述

//hash 散列
#define MAX_SIZE 2048
int *twoSum(int *nums, int numsSize, int target, int *returnSize)
{
    int i, hash[MAX_SIZE], *res = (int *)malloc(sizeof(int) * 2);
    memset(hash, -1, sizeof(hash));
    for (i = 0; i < numsSize; i++)
    {
        if (hash[(target - nums[i] + MAX_SIZE) % MAX_SIZE] != -1)
        {
            res[0] = hash[(target - nums[i] + MAX_SIZE) % MAX_SIZE];
            res[1] = i;
            *returnSize = 2;
            return res;
        }
        hash[(nums[i] + MAX_SIZE) % MAX_SIZE] = i;  //防止负数下标越界,循环散列
    }
    free(hash);
    *returnSize = 0;
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值