关注
在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`。
请注意,这个实现假设数组的大小足够用来作为哈希表的大小,以减少冲突。在实际应用中,你可能需要使用一个更大的哈希表来减少冲突的概率。
查看原帖
点赞 1
相关推荐
点赞 评论 收藏
分享
10-21 20:39
山西大学 电子工程师 点赞 评论 收藏
分享
牛客热帖
正在热议
# 25届秋招公司红黑榜 #
20539次浏览 163人参与
# 在找工作求抱抱 #
817850次浏览 9129人参与
# 字节求职进展汇总 #
276855次浏览 3191人参与
# 一人分享一句让你在秋招振作起来的话 #
10680次浏览 236人参与
# 海康威视求职进展汇总 #
294615次浏览 2820人参与
# 你的简历改到第几版了 #
649502次浏览 9520人参与
# 你最希望上岸的公司是? #
14635次浏览 167人参与
# 海康威视求职进展 #
21804次浏览 153人参与
# 最后再改一次简历 #
1720140次浏览 27398人参与
# 如何写一份好简历 #
557371次浏览 8094人参与
# 找实习多的是你不知道的事 #
1241562次浏览 17611人参与
# 写简历别走弯路 #
585373次浏览 7259人参与
# 我的简历长这样 #
1652843次浏览 25906人参与
# 我想象的实习vs现实的实习 #
215552次浏览 1919人参与
# 你已经投递多少份简历了 #
576573次浏览 7100人参与
# 金融银行求职进展汇总 #
5852次浏览 47人参与
# 产品人求职现状 #
100643次浏览 1306人参与
# 我发现了面试通关密码 #
834559次浏览 14787人参与
# 面试等了一周没回复,还有戏吗 #
76897次浏览 768人参与
# 你收到了团子的OC了吗 #
1007609次浏览 10448人参与