Leetcode[1]-Two Sum
2015-06-09 16:40
344 查看
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
分析:
方法一:使用两个for循环,依次比较,不过这个方法在leetcode上超时了
法二:使用map存储所有的数组值和下标值,然后循环在map中找看能否找到target-nums[i]的map,如果找到了就终止循环,没找到继续找;最后返回index数组;
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
分析:
方法一:使用两个for循环,依次比较,不过这个方法在leetcode上超时了
vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int n = nums.size(); for(int i = 0; i < n ; i++) { index[0] = i+1; for(int j = i+1 ; j < n ; j++) { if(nums[i] + nums[j] == target){ index[1] = j+1; return index; } } } return index; }
法二:使用map存储所有的数组值和下标值,然后循环在map中找看能否找到target-nums[i]的map,如果找到了就终止循环,没找到继续找;最后返回index数组;
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int n = nums.size(); map<int,int> mapv; for(int i = 0; i < n ; i++) { mapv[nums[i]] = i; } map<int,int>::iterator it = mapv.end(); for(int i = 0; i < n; i++) { it = mapv.find(target - nums[i]); if(it != mapv.end() && i!=it->second){ index[0]=min(i+1, it->second + 1); index[1]=max(i+1, it->second + 1); break; } } return index; } };
相关文章推荐
- 2015.6.9 关注设计
- MyEclipse server窗口 Could not create the view: An unexpected exception was thrown 错误解决
- Win10系统向ISO镜像添加语音包解决汉化问题
- nginx 同一个IP上配置多个HTTPS主机
- 歪解Activity生命周期-----初学者彻底理解指南
- 后一个div无法遮挡住前一个有img的div
- 2015年移动金融应用行业报告
- Yii学习笔记之一(安装与基础环境的配置)
- org.tinygroup.application-应用启动框架
- org.tinygroup.xmlparser-XML解析器
- 【Java】【Flume】Flume-NG启动过程源码分析(一)
- mysql_li async 一步查询
- OpenGL顶点数组
- PHP创建缩略图造成图片质量低下的完美解决方法
- C#使用SQLDMO操作数据库的方法
- java 回调函数与匿名内部类
- weblogic学习
- NSTimer解除循环引用
- org.tinygroup.jsqlparser-SQL解析器
- 在MyEclipse下创建Java Web项目 入门(图文并茂)经典教程