[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;
}
相关推荐
Kaltistss42 分钟前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭1 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8241 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug1 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒1 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
努力写代码的熊大2 小时前
单链表和双向链表
数据结构·链表
军训猫猫头2 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
success2 小时前
【爆刷力扣-数组】二分查找 及 衍生题型
算法
Orlando cron2 小时前
数据结构入门:链表
数据结构·算法·链表
牛客企业服务3 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘