问题描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
例如:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
c代码实现
使用utash
由于C语言本身不存在哈希,但是当需要使用哈希表的时候自己构建哈希会异常复杂。因此,我们可以调用开源的第三方头文件,这只是一个头文件:uthash.h。我们需要做的就是将头文件复制到您的项目中,然后:#include “uthash.h”。由于uthash仅是头文件,因此没有可链接的库代码。
以下是下载链接
https://github.com/troydhanson/uthash
#include "stdlib.h"
#include "stdio.h"
#include "uthash-master/src/uthash.h"
/*
HASH_ADD_INT 表示添加的键值为int类型
HASH_ADD_STR 表示添加的键值为字符串类型
HASH_ADD_PTR 表示添加的键值为指针类型
HASH_ADD 表示添加的键值可以是任意类型
*/
typedef struct hash_user_t {
int key;
int value;
UT_hash_handle hh;
} hash_user_t;
void hash_add_user(hash_user_t **user ,int user_key, int user_value)
{
hash_user_t *s = NULL;
HASH_FIND_INT(*user, &user_key, s);
if (s == NULL) {
s = (hash_user_t*)malloc(sizeof(hash_user_t));
s->key = user_key;
HASH_ADD_INT(*user, key, s);
}
s->value = user_value;
}
hash_user_t* hash_find_user(hash_user_t **user, int user_key)
{
hash_user_t *s = NULL;
HASH_FIND_INT(*user, &user_key, s);
return s;
}
int* two_Sum(int* nums, int numsSize, int target, int* returnSize) {
hash_user_t *hash_user_table = NULL;
hash_user_t *hash_find_node = NULL;
for (int i = 0; i < numsSize; i++) {
hash_find_node = hash_find_user(&hash_user_table, target - nums[i]);
if (hash_find_node) {
int *ret = NULL;
ret = (int*)malloc(sizeof(int) * 2);
ret[0] = hash_find_node->value;
ret[1] = i;
*returnSize = 2;
return ret;
}
hash_add_user(&hash_user_table, nums[i], i);
}
*returnSize = 0;
return NULL;
}
int nums[4] = {2,7,11,15};
int *getRes = NULL;
int returnSize = 0;
int main()
{
getRes = twoSum(nums, 4, 18, &returnSize);
if (getRes)
printf("getRes[0] = %d, getRes[1] = %d\n", getRes[0], getRes[1]);
else
printf("NOT FOUND!!!\n");
return 0;
}