Two Sum
2015-09-07 19:44
218 查看
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
struct node{ int val; int pos; }; bool compare (node &a,node &b) { return a.val<b.val; } class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { node tnode[nums.size()]; for(int i=0;i<nums.size();i++) { tnode[i].val=nums[i]; tnode[i].pos=i+1; } sort(tnode,tnode+nums.size(),compare); vector<int> res; int start=0,end=nums.size()-1; while(start<end) { if(tnode[start].val+tnode[end].val==target) {if(tnode[start].pos>tnode[end].pos) swap(tnode[start].pos,tnode[end].pos); res.push_back(tnode[start].pos); res.push_back(tnode[end].pos); return res;} else if(tnode[start].val+tnode[end].val<target) start++; else end--; } } };
vector<int> twoSum(vector<int> &numbers, int target) { map<int, int> mapping; vector<int> result; for(int i =0; i< numbers.size(); i++) { mapping[numbers[i]]=i; } for(int i =0; i< numbers.size(); i++) { int searched = target - numbers[i]; if(mapping.find(searched) != mapping.end()) { result.push_back(i+1); result.push_back(mapping[searched]+1); break; } } return result; }
相关文章推荐
- iOS学习篇章2--Category类别
- 测试和调试的区别
- UISearchBar的基本用法
- android菜鸟进阶之路—— HttpURLConnection 的实例
- HDU5429大数模板
- 回忆丶Java阶段收银系统项目总结
- Linux系统特殊权限
- Objective-C基础知识之(一):类、对象、创建对象、对象操作
- Three.js Projector and Ray objects
- 小胖说事39-----iOS 获取通讯录中联系人的所有属性
- js对象
- linux代理windows上网
- [SPOJ 705] New Distinct Substrings
- 实现从控制台输入字符串,逆序打印输出
- Maven搭建HBase环境报Missing artifact jdk.tools:jdk.tools:jar:1.7
- dispatchTouchEvent onInterceptTouchEvent onTouchEvent区分
- pip安装使用详解
- JDK1.7实现中关于中文编码方案的选取
- linux wc 命令
- vs 2008的相关插件