two sums C语言代码哈希表
时间: 2023-11-29 13:11:18 浏览: 34
以下是使用哈希表解决 Two Sum 问题的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 10000
typedef struct {
int key;
int val;
UT_hash_handle hh;
} HashNode;
HashNode* hashtable = NULL;
void addNode(int key, int val) {
HashNode* node = (HashNode*)malloc(sizeof(HashNode));
node->key = key;
node->val = val;
HASH_ADD_INT(hashtable, key, node);
}
HashNode* findNode(int key) {
HashNode* node = NULL;
HASH_FIND_INT(hashtable, &key, node);
return node;
}
int* twoSum(int* nums, int numsSize, int target) {
int* res = (int*)malloc(2 * sizeof(int));
for (int i = 0; i < numsSize; i++) {
int complement = target - nums[i];
HashNode* node = findNode(complement);
if (node) {
res[0] = node->val;
res[1] = i;
break;
}
addNode(nums[i], i);
}
return res;
}
int main() {
int nums[] = {2, 7, 11, 15};
int target = 9;
int* res = twoSum(nums, sizeof(nums) / sizeof(int), target);
printf("[%d, %d]\n", res[0], res[1]);
free(res);
return 0;
}
```
该代码使用了开源的哈希表库 [uthash](https://github.com/troydhanson/uthash),可通过 `git clone https://github.com/troydhanson/uthash.git` 安装。