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

 

感觉这个题限制太多了,可能会存在重复关键字,且可能是两个重复关键字之和等于target,这种情况下,只能一个关键字取前面的,一个取后面的,不能使两个的索引下标相同。又因为题目保证这样的两个数绝对存在,所以,可以直接让迭代器后移一位,也是相同的关键字。

 

C++代码实现:

#include<map>
#include<iostream>
#include<vector>
using namespace std;

class Solution
{
public:
    vector<int> twoSum(vector<int> &numbers, int target)
    {
        multimap<int,int> sum;
        size_t i=0;
        for(i=0; i<numbers.size(); i++)
            sum.insert({numbers[i],i});
        auto map_it=sum.begin();
        while(map_it!=sum.end())
        {
            int tmp=target-map_it->first;
            auto iter=sum.find(tmp);
            if(iter!=sum.end())
            {
                if(map_it==iter)
                    iter++;
                return vector<int> {min(map_it->second+1,iter->second+1),max(map_it->second+1,iter->second+1)};
            }
            map_it++;
        }
        return vector<int>();
    }
};

int main()
{
    vector<int> vec={0,4,0,3,0};
    Solution s;
    vector<int> result=s.twoSum(vec,0);
    for(auto a:result)
        cout<<a<<" ";
    cout<<endl;
}

运行结果:

可以看看:http://www.acmerblog.com/leetcode-two-sum-5223.html

转载于:https://www.cnblogs.com/wuchanming/p/4101835.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值