[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;
}
相关推荐
Rain的Java大神之路6 分钟前
LeetCode 21 合并两个有序链表:一道 Easy 题,凭什么刷掉一半候选人?
java·后端·算法
小蒋观天下14 分钟前
太阳能低功耗AI相机专项:AOV值守、唤醒时序、ISP启停时序BUG
深度学习·数码相机·算法·机器学习
wenyq721 分钟前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
余额瞒着我当琳23 分钟前
C++异常,异常的概念,异常抛出与捕获,RAII 和智能指针的设计思路,C++标准库一些指针的使用
java·开发语言·c++·算法
東隅已逝,桑榆非晚24 分钟前
map和set的使用
数据结构·c++·笔记·学习
2601_9707038329 分钟前
除湿机原理研究报告:一台机器在物理上能走多远
大数据·数据结构·算法·数据库架构·推荐算法
信奥卷王29 分钟前
[GESP202312 六级] 工作沟通(含视频)
算法
♡すぎ♡38 分钟前
SWE 的原理解析
算法·计算机图形学·swe
AiNightVision41 分钟前
星光级 是什么?——星光级摄像机是什么?0.001Lux 照度门槛与选型真相
人工智能·算法·车载系统·自动驾驶·无人机·视频·智能硬件
若亦_1 小时前
排序>>选择排序
数据结构·算法·排序算法