[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;
}
相关推荐
xiangyun6111 分钟前
【408数据结构 08】队列:循环队列判空判满,408年年考,一次讲清
c语言·开发语言·数据结构·c++·算法
xiangyun6124 分钟前
【408数据结构 06】双链表、循环链表、静态链表
c语言·开发语言·数据结构·c++·算法
OKkankan2 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
蓝速科技2 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发
302wanger2 小时前
推荐下我的两个AI信息源
算法
索尔~古德曼2 小时前
CF——错题的集合
算法
xxwxx__2 小时前
C++ AVL 树深度剖析:平衡二叉搜索树原理、源码与面试考点
数据结构·c++
SL_staff2 小时前
JVS-Logic:从页面配置工具到企业级业务逻辑中枢的技术演进
java·算法·全栈
Logic1012 小时前
C语言/数据结构数组题解:数字列表加一(Plus One)——进位处理与数组扩展
c语言·数据结构·模拟·数组·时间复杂度·算法题·进位
陌シ未央ゞ2 小时前
基于BM25算法和RRF实现的混合索引(java版)
人工智能·spring boot·后端·算法