[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;
}
相关推荐
蒲小英30 分钟前
算法-使用技巧
算法
0x7F7F7F7F33 分钟前
数学知识——博弈论
数学·算法
爱学习的小仙女!1 小时前
顺序表定义、特点和基本操作(含C代码详细讲解)及时间复杂度
数据结构·算法
芥子沫1 小时前
《人工智能基础》[算法篇5]:SVM算法解析
人工智能·算法·机器学习·支持向量机·svm
BigerBang1 小时前
LoRA 全方位指南:从底层原理到 Qwen-Image-Edit 实战
人工智能·pytorch·深度学习·算法
passxgx1 小时前
11.3 迭代法和预条件子
线性代数·算法·矩阵
TechPioneer_lp1 小时前
27届暑期实习内推:网易美团京东快手等
数据结构·c++·人工智能·笔记·机器学习·面试
X在敲AI代码1 小时前
【无标题】
算法·leetcode·职场和发展
bubiyoushang8881 小时前
NSGA-II 带精英策略的双目标遗传算法
算法
qq_430855881 小时前
线代第二章矩阵第八节逆矩阵、解矩阵方程
线性代数·算法·矩阵