LeetCode:1_TwoSum--C++实现

本文介绍了解决LeetCode经典题目“两数之和”的一种实现思路与代码实现过程。该题要求从整数数组中找出两个数,使得它们的和等于特定的目标值,并返回这两个数的索引。

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

本人博客已经迁移到nasdaqgodzilla.github.io

#include <iostream>
#include <vector>

using namespace std;

/*
    LeetCode 1.TwoSum
    题目要求:
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    返回索引位置即可;
    题目假设给出的集合仅仅只有一个满足的a+b==target:assume that each input would have exactly one solution

	====================
	想到另一种办法:用target-a得到b,在集合中搜索存不存在b即可;可以使用HashMap等快速搜索容器
	====================
*/
vector<pair<int,int>> two_sum(vector<int>& nums,int target)
{
    //auto iter = nums.cbegin();
    vector<pair<int,int>> ret;                 //容纳返回值
    int sum = 0;
    int first_index = 0;                        //a+b==target中a的索引位置
    int index = -1;                             //循环次数:对应nums中的索引
    bool hadFirst = false;                      //是否已取得第一个数

    for(auto i : nums){
        ++index;
        if(i > target)
            continue;
        if(sum + i > target)
            continue;
        if(hadFirst)
        {
            if(sum + i == target)
            {
                ret.push_back(pair<int,int>{first_index,index});
                hadFirst = false;
                sum = 0;
            }
            else    //sum + i < target
                continue;
        }
        else
        {
            first_index = index;
            sum = i;
            hadFirst = true;
        }
    }

    return ret;
}

int main()
{
    vector<int> nums = {20,2,7,5,8,11,9,3};
    int target = 10;
    auto ret = two_sum(nums,target);

    for(auto i : ret)
    {
        cout<<i.first<<":"<<i.second<<"<--->"
            <<nums[i.first]<<"+"<<nums[i.second]<<"=="<<target<<endl;
    }

    return 0;
}

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值