LeetCode:Two Sum
2015-06-03 20:29
507 查看
问题描述:
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
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { unordered_map<int,int> datamap; vector<int> result; for(int i=0;i<numbers.size();i++) { datamap[numbers[i]]=i; } for(int i=0;i<numbers.size();i++) { int gap=target-numbers[i]; if(datamap.find(gap)!=datamap.end()&&datamap[gap]!=i) { result.push_back(i+1); result.push_back(datamap[gap]+1); break; } } return result; } };
相关文章推荐
- Hibernate - DetachedCriteria 的完整用法
- 四方定理
- GDB调试器使用总结
- 环形缓冲区的设计与实现
- ViewPager onPageChangeListener总结
- Javascript 中的非空判断 undefined,null, NaN的区别
- javaWeb学习笔记3
- POJ 2376 Cleaning Shifts
- eclipse 无法调试Junit的TestCase
- BZOJ3895 rock
- c++输入文件处理按行读取并且将实现对一行数据分别处理
- xi and bo (并查集问题)
- Convert Sorted List to Binary Search Tree ------C++ 递归创建平衡二叉查找树
- Putting it Together: Understanding Pointers
- iOS 定制手机通讯录(4)
- win8.1分区
- 黑马程序员——C语言基础——结构体以及结构体指针实战
- JavaScirpt事件处理
- iOS 定制手机通讯录(3)
- 这个博客目前不更新了,请关注另外一个博客!