[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;
}
相关推荐
NAGNIP5 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队6 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja11 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下11 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶11 小时前
算法 --- 字符串
算法
博笙困了11 小时前
AcWing学习——差分
c++·算法
NAGNIP11 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP11 小时前
大模型微调框架之LLaMA Factory
算法
echoarts11 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客11 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法