首页 > 代码库 > Two Sum

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

思路:使用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