[LeetCode]Two Sum

本文介绍了一个算法,用于在给定数组中找到两个数,它们相加等于特定的目标数。通过使用哈希表,我们可以在O(n)时间内解决此问题,并确保返回的索引满足题目要求。

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

这里需要注意返回的是索引,所以需要记录一下。如果有两个元素的值一样大,那么还需要注意使用哈希表存储的时候要把第一次查询到的删掉。

例如:5 2 3 2 ,target = 4时,那么返回的索引应该是 2 4

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        unordered_multimap<int,int> nimap;
        for (int i = 0; i < numbers.size(); i++)
            nimap.insert(make_pair(numbers[i], i+1));
        sort(numbers.begin(), numbers.end());
        size_t i = 0, j = numbers.size() - 1;
        while(i < j)
        {
            int a = numbers[i], b = numbers[j];
            if (a + b == target)
            {
                auto ite1 = nimap.find(a);
                nimap.erase(ite1);
                auto ite2 = nimap.find(b);
                result.push_back(ite1->second);
                result.push_back(ite2->second);
                if (result[0] > result[1])
                    swap(result[0], result[1]);
                return result;
            }
            else if (a + b < target)
                ++i;
            else
                --j;
        }
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值