1.
class Solution {public: vector twoSum(vector &numbers, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. mapmp; int len = numbers.size(); for( int i=0; i < len; ++i ) { mp[ numbers[ i ] ] = i + 1; } vector result; for( int i = 0; i < len; ++i ) { map ::iterator it = mp.find( target - numbers[i] ); if( it != mp.end() ) { result.push_back(it->second); result.push_back(i+1); sort(result.begin(),result.end()); break; } } return result; };};
使用multimap实现;比较笨的方法(map中的键值对是按键排序粗放的)。
class Solution {public: vector twoSum(vector &numbers, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. multimaptmp; for( int i = 1; i <= numbers.size(); ++i ) { tmp.insert(pair (numbers[i-1],i)); } multimap ::iterator index1= tmp.begin(); multimap ::iterator index2 = --tmp.end(); while( index1 != index2 ) { int sum = index1->first + index2->first; if( sum > target ) --index2; else if( sum < target ) ++index1; else break; } vector result; if(index1->second > index2->second) { int tmp = index1->second ; index1->second =index2->second ; index2->second=tmp; } result.push_back(index1->second); result.push_back(index2->second); return result; }};