Two Sum
2016-02-28 19:17
309 查看
Description:
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
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
// 用一个hash表,存储每个数的下标,复杂度O(n) #include <iostream> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: vector<int> twoSum(vector<int> &num, int target) { unordered_map<int,int>mapping; vector<int> result; for (int i=0; i < num.size() ; ++i ) { mapping[num[i]] = i; } for (int i=0; i < num.size(); ++i) { const int remain = target - num[i]; if (mapping.find(remain) != mapping.end() && mapping[remain] > i) { result.push_back(i+1); result.push_back(mapping[remain]+1); break; } } return result; } }; int main() { vector<int> num={2,7,11,15}; vector<int> result; Solution solution; result = solution.twoSum(num,9); for( auto it=result.cbegin(); it !=result.cend(); ++it) cout<<*it<<" "; cout<<endl; return 0; }
相关文章推荐
- 进制
- 关于开展城乡居民大病保险工作的指导意见
- 迭代器
- USACO1.3:milk
- (android高仿系列)今日头条 --新闻阅读器 (三) 完结 、总结 篇
- Maven单元测试报告及测试覆盖率
- node.js定时事务node-schedule
- HDU 5538 House Building [Ad Hoc]
- USACO1.2:milk2
- logback日志写入数据库的配置
- JVM原理和优化
- android中基本文件输入输出流的使用(代码)
- (android高仿系列)今日头条 --新闻阅读器 (二)
- POJ2796 Feel Good(单调栈)
- POJ 3273 Monthly Expense (二分搜索)
- USACO1.5:sprime
- Java处理图片缩放,水印的利器 thumbnailator
- 【redis 基础篇二】redis安装-Linux服务
- 如何官网下载最新Genymotion
- 对接口、继承、组合、多态的理解