1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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.