[Leetcode学习-C语言]Two Sum

题目连接:LeetCode - The World's Leading Online Programming Learning Platform

leetcode写C真的很多坑......

用 hash 拉链法 构造hash函数,才能写这么题小题。

cpp 复制代码
 typedef struct Node {  // 得自己做个hash 拉链法
     struct Node *next;
     int val;
     int sign;
 }Node, * pNode;

 void insert(int val, int sign, int hash, pNode nodeList[]) {
    pNode newNode = (pNode) malloc(1 * sizeof(Node));
    newNode->val = val;
    newNode->sign = sign;
    newNode->next=NULL; // leetCode的检测问题需要置空
    //printf("  a");
    if(nodeList[hash]) {
        pNode node = nodeList[hash];
        while(node->next) {
            node = node->next;
        }
        node->next = newNode;
    } else {
        nodeList[hash] = newNode;
    }
 }
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    *returnSize = 2; // leetCode需要指定返回多少数字
    int *result = (int*)malloc(sizeof(int)*2); // leetCode避免内存被清空
    int point1, point2, find = 0;
    pNode nodeList[10000] = {0}; // 这里能写成动态分配内存就好了
    // for(int i = 0; i < numsSize; i ++) printf("%d ", nums[i]);
    for(int i = 0; i < numsSize; i ++) {
        int val = target - nums[i];
        int hash = abs(val % numsSize);  // 做取余
        //printf("%d  ", hash);
        if(nodeList[hash]) {
            pNode nodeI = nodeList[hash];
            //printf("  %d|%d  ", nodeI->val, val);
            while(nodeI) {
                if((nodeI->val) == val) {
                    point1 = nodeI->sign;
                    point2 = i;
                    find = 1;
                    break;
                }
                nodeI = nodeI->next;
            }
        }
        if(find) break;
        insert(nums[i], i, abs(nums[i] % numsSize), nodeList);
    }
    result[0] = point1;
    result[1] = point2;
    //printf("\n%d %d", point1, point2);
    return result;
}
相关推荐
良月澪二25 分钟前
CSP-S 2021 T1廊桥分配
算法·图论
wangyue41 小时前
c# 线性回归和多项式拟合
算法
&梧桐树夏1 小时前
【算法系列-链表】删除链表的倒数第N个结点
数据结构·算法·链表
QuantumStack1 小时前
【C++ 真题】B2037 奇偶数判断
数据结构·c++·算法
今天好像不上班2 小时前
软件验证与确认实验二-单元测试
测试工具·算法
wclass-zhengge2 小时前
数据结构篇(绪论)
java·数据结构·算法
Dylanioucn2 小时前
【分布式微服务云原生】探索Redis:数据结构的艺术与科学
数据结构·redis·分布式·缓存·中间件
何事驚慌2 小时前
2024/10/5 数据结构打卡
java·数据结构·算法
结衣结衣.2 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
大三觉醒push亡羊补牢女娲补天版2 小时前
数据结构之排序(5)
数据结构