Two Sum

博客围绕给定整数数组,找出两数之和等于特定目标数的问题展开。给出了两种解法,一种使用hash表,另一种是先排序再用首尾指针遍历。还提到使用hash表的解法原理类似暴力破解,不算好。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

相信当你看见这篇博客时,已经独立思考过,这里直接给出Accepted Code。部分代码来自网络,希望不会涉及版权问题。

Solution1:

vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> res(2);
    int n = nums.size();
    if(n < 2)
        return res;
    unordered_map<int, int> map;
    unordered_map<int, int>::const_iterator it = map.end();
    int tmp;
    for (int i = 0;i < n;++i)
    {
        tmp = target - nums[i];
        it = map.find(tmp);
        if (it != map.end())
        {
            res[0] = it->second + 1;
            res[1] = i + 1;
            return res;
        }
        else
            map[nums[i]] = i;
    }
}

 

后记

  这道题还有一种解法就是先排序,然后首尾两个指针遍历寻找。上述使用hash表的解法,其原理依旧是暴力破解,并不算好。(今天做3Sum有感)

solution2:

struct Node{
    int id,val;
};
bool compare(const Node &a, const Node &b){
    return a.val < b.val;
}

vector<int> twoSum(vector<int> &numbers, int target) {
    vector<Node> nodes(numbers.size());
    for(int i = 0;i < numbers.size();++i){
        nodes[i].id = i+1;
        nodes[i].val = numbers[i];
    }
    sort(nodes.begin(),nodes.end(),compare);
    int start = 0, end = numbers.size()-1;
    vector<int> res;
    while(start < end){
        if(nodes[start].val + nodes[end].val == target){
            if(nodes[start].id > nodes[end].id)
                swap(nodes[start].id , nodes[end].id);
            res.push_back(nodes[start].id);
            res.push_back(nodes[end].id);
            return res;
        }
        else if( nodes[start].val + nodes[end].val < target )
            ++start;
        else
            --end;
    }
}

 

转载于:https://www.cnblogs.com/gattaca/p/4122041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值