leetcode 1 -- Two Sum

本文探讨了如何在整数数组中寻找两个数使它们的和等于特定目标值的问题,并详细介绍了使用二叉搜索树来优化查找过程的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

这道题做的真是一波三折…

题目

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意

给定一序列和一数值target,返回序列中和为target的两数的下标,用数组保存,返回数组指针

思路

刚开始想取巧,想用f[nums[i]]=i 保存数值与下表 来搞定,显然是低估了 出题人员的智商,测试数据又是负数,又是含两个0的,搞得wrong不断
之后用暴力尝试了下,不出所料,超时
细细思考发现关键就在于如何快速对序列项进行查找,自然就想到二叉搜索树

代码

int* twoSum(int* nums, int numsSize, int target) {
    int i,j,flag;
    int *a=(int*)malloc(sizeof(int)*3);
    struct Node
    {
        int val;
        int num;
        struct Node *l,*r;
    }*p,*q,*root;
    root=(struct Node*)malloc(sizeof(struct Node));
    root->val=nums[0];
    root->num=0;
    root->l=NULL;
    root->r=NULL;
    for(i=1;i<numsSize;i++)
    {
        p=root;
        flag=target-nums[i];
        while(p!=NULL)//在树中查找是否存在值等于flag
        {
            if(flag==p->val)//存在则直接对a赋值并返回
            {
                a[0]=p->num+1;
                a[1]=i+1;
                return a;
            }
            if(flag<p->val)
            {
                p=p->l;
            }
            else if(flag>p->val)//此处一定要加else 因为 p=p->l后 若p=NULL 接下来 flag<p->val 会引起段错误...
            {
                p=p->r;
            }
        }
        p=(struct Node*)malloc(sizeof(struct Node));
        p->val=nums[i];
        p->num=i;
        p->r=p->l=NULL;
        q=root;
        while(1)//nums[i]加入搜索树
        {
            if(nums[i]>=q->val)
            {
                if(q->r==NULL)
                {
                    q->r=p;
                    break;
                }
                else
                {
                    q=q->r;
                }
            }
            else if(nums[i]<q->val)
            {
                if(q->l==NULL)
                {
                    q->l=p;
                    break;
                }
                else
                {
                    q=q->l;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值