LeetCode:1_TwoSum--C++实现

来源:互联网 发布:笔记本电脑必备软件 编辑:程序博客网 时间:2024/06/10 15:29
#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.

原创粉丝点击