Two Sum
来源:互联网 发布:守望先锋生涯数据 编辑:程序博客网 时间:2024/05/12 03:04
Two Sum
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
解题思路:用unordered_map,首先开始一个循环,如果没有找到元素与映射中的值相加等于target
(即find函数的返回值指向end()),就插入映射继续查找,否则查找成功。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int i; vector<int> vint; unordered_map<int,int> unmap; unordered_map<int,int>::iterator iter; for(i = 0;i <nums.size();++i) { if(( iter=unmap.find(target - nums[i])) == unmap.end()) unmap.insert(make_pair(nums[i],i)); else { vint.push_back(iter->second + 1); vint.push_back(i+1); break; } } return vint; }};
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- hdu 5307 He is Flying 2015 Multi-University Training Contest 2 快速傅里叶变换
- 堆和栈的区别(转过无数次的文章)
- Veriog_Notes_Chapter 1
- 学习集合Collection , Map
- 史上最强劲的android模拟器命令详解
- Two Sum
- hdu5246 贪心
- “计蒜客”-挑战难题-14:罗马数字转换成整数
- python---mongodb
- 工程日记的重要性
- 命令执行顺序控制与管道
- 改变第一天,记录每一天
- java常量使用
- oc014---oc的数据类型