一、题目描述
二、思路
两种解法:暴力解法和哈希表,哈希表的话好麻烦!!!但是因为对ut_hash的使用不熟悉,所以打算用哈希表来解。由于C语言本身不存在哈希表,因此我们可以调用开源的第三方头文件:c开源hash项目 uthash的用法总结 | C语言哈希表UT_hash的使用方法详解 | 代码随想录:哈希表解法
三、解题过程
-
定义一个键为int类型的hash结构体
- 其中key存储num[ i ]的值,index存储各个值的下标:
typedef struct hhMap {
int key;
int index;
UT_hash_handle hh;
}map;
map* hashMap = NULL;
-
实现查找接口函数
map* hashMapFind (int key) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
return s;
}
-
实现插入接口函数
void hashMapAdd (int key, int index) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s == NULL) {
s = (map*)malloc(sizeof(map));
s -> key = key;
HASH_ADD_INT(hashMap, key, s);
}
s -> index = index;
}
-
实现清空哈希表函数
void deleteHash () {
map *cur, *tmp;
HASH_ITER(hh, hashMap, cur, tmp){
HASH_DEL(hashMap, cur);
free(cur);
}
}
-
twoSum函数:
-
遍历数组并将每个值放入哈希表中
int i = 0;
for(; i < numsSize; i ++) {
hashMapAdd(nums[i], i);
}
-
不理解的步骤...:
printHash();
/*它的实现函数如下:(因为不理解它的功能,所以没放在上边)
void printHash () {
map* s = hashMap;
for(; s; s = (map*)(s -> hh.next)) {
printf("key: %d ,index: %d", s -> key, s -> index);
}
}
*/
-
寻找能相加等于target的元素下标
- 若找得到则return ans(记录答案下标的数组),若找不到则return NULL:
int* ans = (int*)malloc(sizeof(int) * 2);
map* hashFindRes;
for(i = 0; i < numsSize; i ++) {
hashFindRes = hashMapFind(target - nums[i]);
if(hashFindRes && hashFindRes -> index != i){
ans[0] = i;
ans[1] = hashFindRes -> index;
* returnSize = 2;
deleteHash();
return ans;
}
}
deleteHash();
return NULL;
四、代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct hhMap {
int key;
int index;
UT_hash_handle hh;
}map;
map* hashMap = NULL;
map* hashMapFind (int key) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
return s;
}
void hashMapAdd (int key, int index) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s == NULL) {
s = (map*)malloc(sizeof(map));
s -> key = key;
HASH_ADD_INT(hashMap, key, s);
}
s -> index = index;
}
void deleteHash () {
map *cur, *tmp;
HASH_ITER(hh, hashMap, cur, tmp){
HASH_DEL(hashMap, cur);
free(cur);
}
}
void printHash () {
map* s = hashMap;
for(; s; s = (map*)(s -> hh.next)) {
printf("key: %d ,index: %d", s -> key, s -> index);
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i = 0;
for(; i < numsSize; i ++) {
hashMapAdd(nums[i], i);
}
printHash();
int* ans = (int*)malloc(sizeof(int) * 2);
map* hashFindRes;
for(i = 0; i < numsSize; i ++) {
hashFindRes = hashMapFind(target - nums[i]);
if(hashFindRes && hashFindRes -> index != i){
ans[0] = i;
ans[1] = hashFindRes -> index;
* returnSize = 2;
deleteHash();
return ans;
}
}
deleteHash();
return NULL;
}
五、遇到的问题
- 不理解printHash的功能:删掉也能通过,但是代码随想录中存在这一行代码;