[Leetcode]1Two Sum
来源:互联网 发布:python和javascript 编辑:程序博客网 时间:2024/04/25 13:11
Given an array of inergers, 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
方法一:
使用STL中定义的unorder_map将vector中元素的value 和 indice存入。遍历数组,找到两个相加是target的值。
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { unordered_map<int, int> mapping;vector<int> results;for(int i = 0; i < numbers.size(); ++i){mapping[numbers[i]] = i;}for(int i = 0; i < numbers.size(); ++i){const int gap = target - numbers[i];if(mapping.find(gap) != mapping.end() && mapping[gap] > i){results.push_back(i+1);results.push_back(mapping[gap]+1);break;}}return results; }};
</pre><pre code_snippet_id="621500" snippet_file_name="blog_20150317_4_3955113" name="code" class="cpp"><pre name="code" class="cpp">class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { int i, sum; vector<int> results; map<int, int> hmap; for(i=0; i<numbers.size(); i++){ if(!hmap.count(numbers[i])){ hmap.insert(pair<int, int>(numbers[i], i)); } if(hmap.count(target-numbers[i])){ int n=hmap[target-numbers[i]]; if(n<i){ results.push_back(n+1); results.push_back(i+1); //cout<<n+1<<", "<<i+1<<endl; return results; } } } return results; }};
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- SQL SERVER数据库修改是否区分大小写
- [转载] Ubuntu14.04下hadoop-2.6.0单机配置和伪分布式配置
- poj_3278
- 19.最省钱的app发短信方法
- 在 ServiceModel 客户端配置部分中,找不到引用协定“PutMCCases.PutMCCasesSoap”的默认终结点元素。这可能是因为未找到应用程序的配置文件,或者是因为客户端元素中找不到
- [Leetcode]1Two Sum
- 面试题
- EGOimage 和 SDWebImage
- 实现微信一样下拉加载朋友圈
- linux查看进程的执行文件路径
- MySQL修改密码与更改默认编码
- HTTP协议详解
- Javascript入门
- shell脚本中执行命令的疑难浅析