LeetCode --- Two Sum

来源:互联网 发布:网络外汇销售的骗局 编辑:程序博客网 时间:2024/05/21 06:21

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=9Output: index1=1, index2=2

Submitted Code

#include<iostream>#include<map>using namespace std;class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        std::multimap<int,int> intMap;        vector<int> ret;        int index=0;        int size=numbers.size();        for(;index<size;++index){            intMap.insert(pair<int, int>(numbers.at(index),index));        }        std::multimap<int,int>::iterator iiter=intMap.begin();        std::multimap<int,int>::iterator low,high;        for(;iiter!=intMap.end();++iiter){            if(iiter->first <= target){                if(intMap.count(target-iiter->first)>0){                    low=intMap.lower_bound(target-iiter->first);                    high=intMap.upper_bound(target-iiter->first);                    while(low!=high){                        ret.push_back(iiter->second+1);                        if((low!=iiter)&&low->second>iiter->second){                             ret.push_back(low->second+1);                             return ret;                        }else{                            ret.clear();                            ++low;                        }                    }                }            }            else{                break;            }        }        return ret;    }};
0 0
原创粉丝点击