LeetCode:1_TwoSum--C++实现

#include 
#include 

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等快速搜索容器
    ====================
*/
vectorint,int>> two_sum(vector<int>& nums,int target)
{
    //auto iter = nums.cbegin();
    vectorint,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<":"<"<--->"
            <"+"<"=="<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.

你可能感兴趣的:(C++,leetcode)