Leetcode::Two Sum
1.
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. map<int,int> mp; int len = numbers.size(); for( int i=0; i < len; ++i ) { mp[ numbers[ i ] ] = i + 1; } vector<int> result; for( int i = 0; i < len; ++i ) { map<int,int>::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<int> twoSum(vector<int> &numbers, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. multimap<int,int> tmp; for( int i = 1; i <= numbers.size(); ++i ) { tmp.insert(pair<int,int>(numbers[i-1],i)); } multimap<int,int>::iterator index1= tmp.begin(); multimap<int,int>::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<int> 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; } };