两数之和
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;
- 首先初始化 hash[2000], 初始值设为 -1 ,
遍历数组, 查看 target - nums[i] 为下标 的 hash 数组元素值 (hash[ target - nums[i] ]) 是否为 - 1; - 若为 -1 ,将 下标 i 存放在 hash数组的 nums[i] 位置上, hash[ nums[i] ] = i;
- 若不为 -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;
}