题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路
由于在C语言中采用hash结构比较复杂,此处直接采用数组散列,将数组中的元素作为下标,下标作为对应元素进行散列,由于考虑到目标值减去其中某个值的数会为负数,因此将其往数组尾部进行散列。
代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_SIZE 2048
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int hash[MAX_SIZE];
int * res = (int *)malloc(sizeof(int) * 2);
memset(hash, -1, sizeof(hash));
for(int 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;
}