在C语言中,你可以使用哈希表的方法来解决这个问题。下面是一个使用哈希表的C语言实现示例:
```c
#include <stdio.h>
(30951)#include <stdlib.h>
// 定义哈希表节点结构体
typedef struct HashNode {
int key;
int value;
struct HashNode* next;
} HashNode;
// 创建哈希表节点
HashNode* createNode(int key, int value) {
HashNode* newNode = (HashNode*)malloc(sizeof(HashNode));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 计算哈希值
int hash(int key, int size) {
return key % size;
}
// 插入哈希表
void insert(HashNode** hashTable, int key, int value, int size) {
int index = hash(key, size);
HashNode* newNode = createNode(key, value);
newNode->next = hashTable[index];
hashTable[index] = newNode;
}
// 查找哈希表
HashNode* search(HashNode** hashTable, int key, int size) {
int index = hash(key, size);
HashNode* temp = hashTable[index];
while (temp != NULL) {
if (temp->key == key) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// 释放哈希表
void freeHashTable(HashNode** hashTable, int size) {
for (int i = 0; i < size; i++) {
HashNode* temp = hashTable[i];
while (temp != NULL) {
HashNode* next = temp->next;
free(temp);
temp = next;
}
}
free(hashTable);
}
// 两数之和
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int hashSize = numsSize;
HashNode** hashTable = (HashNode**)calloc(hashSize, sizeof(HashNode*));
int* result = (int*)malloc(2 * sizeof(int));
*returnSize = 2;
for (int i = 0; i < numsSize; i++) {
int complement = target - nums[i];
HashNode* node = search(hashTable, complement, hashSize);
if (node != NULL) {
result[0] = node->value;
result[1] = i;
freeHashTable(hashTable, hashSize);
return result;
}
insert(hashTable, nums[i], i, hashSize);
}
freeHashTable(hashTable, hashSize);
*returnSize = 0;
return NULL;
}
int main() {
int nums[] = {2, 7, 11, 15};
int target = 9;
int returnSize;
int* indices = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize);
if (indices != NULL) {
printf("Indices are: %d, %d\n", indices[0], indices[1]);
} else {
printf("No solution found.\n");
}
free(indices);
return 0;
}
```
这段代码首先定义了一个哈希表节点结构体,然后实现了创建节点、计算哈希值、插入和查找哈希表的功能。`twoSum` 函数使用哈希表来查找和为 `target` 的两个整数的下标。如果找到了,就返回它们的下标;如果没有找到,就返回 `NULL`。
请注意,这个实现假设数组的大小足够用来作为哈希表的大小,以减少冲突。在实际应用中,你可能需要使用一个更大的哈希表来减少冲突的概率。