[LeetCode]Two Sum

来源:互联网 发布:ubuntu samba 写权限 编辑:程序博客网 时间:2024/06/04 06:38
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


这个能写出来真是开心啊。。虽然花了很多的时间,但是没有参照师兄的代码,用的是最近刚学到的multimap。
题目的关键在于数字可以重复,但如果两倍重复的数字不等于targets,则可以忽略,因为最后的结果是唯一的。

multimap写起来很麻烦,但是很好用,速度也快。


#include <algorithm>#include <vector>#include <iostream>#include <map>using namespace std;class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int>vecAnswer;        multimap<int,int>mapAnswer;        for(int i=0;i<numbers.size();i++)        {            mapAnswer.insert(make_pair(numbers[i],i+1));        }        multimap<int,int>::iterator iterLeft=mapAnswer.begin();        multimap<int,int>::iterator iterRight=--mapAnswer.end();        while(iterLeft!=iterRight)        {            if(mapAnswer.count(iterLeft->first)>1 &&         //判断是否有重复               mapAnswer.count(iterLeft->first)*2==target)  //判断重复数的两倍是否等于target               {                    vecAnswer.push_back(mapAnswer.find(iterLeft->first)->second);                    vecAnswer.push_back((++mapAnswer.find(iterLeft->first))->second);                    break;               }            if(mapAnswer.count(iterRight->first)>1 &&               mapAnswer.count(iterRight->first)*2==target)               {                    vecAnswer.push_back(mapAnswer.find(iterRight->first)->second);                    vecAnswer.push_back((++mapAnswer.find(iterRight->first))->second);                    break;               }            int sum=(iterLeft->first)+(iterRight->first);            if(sum>target)iterRight--;            else if(sum<target)iterLeft++;            else            {                vecAnswer.push_back(iterLeft->second);                vecAnswer.push_back(iterRight->second);                break;            }        }        sort(vecAnswer.begin(),vecAnswer.end());        return vecAnswer;    }};int main(){    int  target=100;    vector<int>vec;    vec.push_back(5);    vec.push_back(75);    vec.push_back(25);    vec.push_back(0);    Solution sol;    sol.twoSum(vec,target);}


0 0
原创粉丝点击