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不断
之后用暴力尝试了下,不出所料,超时
细细思考发现关键就在于如何快速对序列项进行查找,自然就想到二叉搜索树
代码
这道题做的真是一波三折…
题目
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; } } } } }
相关文章推荐
- 记录一篇人工智能的内容!
- 多线程(初级篇)
- JDK,JRE,JVM区别与联系
- 2015061402 - 如果每天阅读了一本书?
- [HackerRank] The Longest Common Subsequence
- 如何让两个div并排同行显示
- 函数编译与执行及虚函数剖析(源码论证)
- 绕过cdn-寻找真实的IP
- java对象克隆之深度克隆 deep clone
- 《你的灯还亮着吗》 阅读笔记一
- Android性能优化典范
- 基于Nginx反向代理的SparkUI的访问
- hdu 1496 Equations (hash)
- C#接口
- dubbo原理
- LeetCode 104 Maximum Depth of Binary Tree
- Info.plist:项目配置文件
- 驰骋工作流引擎功能新增操作提示
- 第二次冲刺阶段 站立会议09
- java 框架基础知识(5)----注解-->Spring配置