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

Two Sum

时间:2014-09-07 23:40:25      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   使用   ar   for   div   

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

思路:使用map保存已经访问过的元素。

 1 class Solution {
 2 public:
 3     vector<int> twoSum( vector<int> &numbers, int target ) {
 4         vector<int> ret( 2, -1 );
 5         unordered_map<int,int> idxMap;
 6         int size = numbers.size();
 7         for( int i = 0; i < size; ++i ) {
 8             auto iter = idxMap.find( numbers[i] );
 9             if( iter != idxMap.end() ) {
10                 ret[0] = min( iter->second, i+1 );
11                 ret[1] = max( iter->second, i+1 );
12                 break;
13             } else {
14                 idxMap[ target-numbers[i] ] = i+1;
15             }
16         }
17         return ret;
18     }
19 };

 

Two Sum

标签:style   blog   color   os   io   使用   ar   for   div   

原文地址:http://www.cnblogs.com/moderate-fish/p/3960853.html

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