two sum
2015-07-17 10:04
295 查看
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
另一种方法:
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
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { typedef pair<int,int>pa; vector<int>ans; map<int,int> mymap; int i; for(i=0;i<numbers.size();i++){ mymap.insert(pa(numbers[i],i)); if(mymap.count(target-numbers[i])){ int n=mymap[target-numbers[i]]; if(n<i){//delself ans.push_back(n+1); ans.push_back(i+1); return ans; } } } } };
另一种方法:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int>array(numbers.size()); array=numbers; sort(array.begin(),array.end()); auto i=array.begin(),j=--array.end(); int sum=*i+*j; while(i<j) { sum=*i+*j; if(sum==target) break; else if(sum>target) --j; else ++i; } int ii,jj; for(ii=0;ii<numbers.size();ii++){ if(*i==numbers[ii]) break; } for(jj=numbers.size()-1;jj>=0;jj--){ if(*j==numbers[jj]) break; } int min=ii>jj?jj:ii; int max=ii>jj?ii:jj; return vector<int>{++min,++max}; } };
相关文章推荐
- MySQL的varchar定义长度到底是字节还是字符
- The General Procedure Of Setting Up EDKII Development Environment:搭建EDKII开发环境的通用流程[2.1]
- 关于quartus ii软件中注释乱码问题的解决方法
- hdoj1903
- 动态计算UITableViewCell高度详解
- 解决VM克隆网卡无法识别
- Laucnher3如何实现给hotseat上的应用显示title
- leetCode(39):Lowest Common Ancestor of a Binary Tree
- Java 重写hashCode 方法和equals方法
- 经典SQL语句大全
- leetCode(39):Lowest Common Ancestor of a Binary Tree 分类: leetCode 2015-07-17 10:03 114人阅读 评论(0) 收藏
- 金错刀:【马化腾的红包:一款7星级产品如何炼成?】
- 最后一周 银行储蓄系统
- HDU 1005 Number Sequence
- js 关于table的操作
- C++11/14 lamba, 仿函数 对比
- error PRJ0019:A Tool returned an error code from"XX.moc"
- JVM概述
- hdoj1902
- UITableviewCell使用以及自定义高度