1. 两数之和
此题是可以理解为查找、添加类题目,是典型的hash做法,可以使用uthash来实现,代码如下:
typedef struct {
int key;
int val;
UT_hash_handle hh;
} my_hash;
my_hash *g_user;
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i;
g_user = NULL;
my_hash *tmp = NULL;
int *res = malloc(2 * sizeof(int));
*returnSize = 2;
for(i = 0; i<numsSize; i++) {
int to_find = target - nums[i];
HASH_FIND_INT(g_user, &to_find, tmp);
if(tmp == NULL) {
tmp = malloc(sizeof(my_hash));
tmp->key = nums[i];
tmp->val = i;
HASH_ADD_INT(g_user, key, tmp);
} else {
res[0] = tmp->val;
res[1]= i;
break;
}
}
return res;
}

浙公网安备 33010602011771号