LeetCode001 两数之和

纯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实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值