纯C实现,没有使用uthash。
(1)哈希表结构:结构体指针数组
(2)哈希函数:余数法,选择11为除数
(3)处理冲突的方法:拉链法
typedef struct number{
int num;
int val;
struct number* pNext;
}Node,*pNode;
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
pNode hashtable[21] = { NULL };//用于插入新结点
pNode pcur[21] = { NULL };//用于遍历
pNode tag[21] = { NULL };//用于站位
for (int i = 0; i < numsSize; i++) {
int j = (target - nums[i]) % 11 + 10;//要考虑负数
int m = nums[i] % 11+10;
while (NULL != pcur[j]) {
if (target == pcur[j]->val + nums[i]) {
int* a = (int*)calloc(2, sizeof(int));
a[0] = pcur[j]->num;
a[1] = i;
*returnSize = 2;
return a;
}
else {
pcur[j] = pcur[j]->pNext;
}
}
pcur[j] = tag[j];//遍历没有找到目标,返回头结点
if (NULL != hashtable[m]) {
pNode pnew = (pNode)calloc(1, sizeof(Node));
pnew->num = i;
pnew->val = nums[i];
hashtable[m]->pNext = pnew;
hashtable[m] = hashtable[m]->pNext;
//hashtable[m]指针如不为空,则始终在倒数第二的位置
}
else {
pNode pnew = (pNode)calloc(1, sizeof(Node));
pnew->num = i;
pnew->val = nums[i];
hashtable[m] = pnew;
pcur[m] = pnew;
tag[m] = pnew;
}
}
*returnSize = 0;
return NULL;
}
(4)以下是时间、空间复杂度:
(5)仍然有提高的空间,尝试使用uthash的开源包或者用Java实现