码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum

时间:2015-01-06 00:42:58      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

 1 Given an array of integers, find two numbers such that they add up to a specific target number.
 2 
 3 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.
 4 
 5 You may assume that each input would have exactly one solution.
 6 
 7 Input: numbers={2, 7, 11, 15}, target=9
 8 Output: index1=1, index2=2
 9 
10 
11 
12 #include<map>
13 using namespace std;
14 
15 class Solution {
16 public:
17     vector<int> twoSum(vector<int> &numbers, int target) {
18         //思路: 用target = a + b ====> a = target -b; 
19         //利用hash 表 , 首先把每个数对应的下标存起来, 在map 里卖遍历一次就行。num1 = target - numb2(numb2 直接在数组中取就行了)
20         map<int , int > mapping;
21         vector<int> result;
22         for(int i = 0 ; i < numbers.size(); ++i)
23         {
24             mapping[numbers[i]] = i;
25         }//缓存每个数字对应的下标, 因为题目要求是要返回下标的。
26         
27         for(int i = 0; i < numbers.size(); ++i)
28         {
29             const int num1 = target - numbers[i];
30             if((mapping.find(num1) != mapping.end()) && mapping[num1] != i) 
31             {//19 行 如果没有加入 mapping[num1] != i 的话有个测试用例 比如 [3, 2 , 4] 就过不了,没加返回的是 1 1
32                 result.push_back(i + 1);
33                 result.push_back(mapping[num1] + 1);//因为是从0开始存储的, 所以返回下标的时候要 加上1;
34                 break; //找到之后立马退出来。
35             }
36         }
37         return result;
38     }
39 };

 

Two Sum

标签:

原文地址:http://www.cnblogs.com/clm-beigong/p/4204854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!