您的位置:首页 > 其它

leetcode 1 -- Two Sum

2015-06-14 23:10 309 查看
前言

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

题目

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;
                }
            }
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: