-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.cpp
More file actions
44 lines (40 loc) · 1.09 KB
/
Copy pathtwo_sum.cpp
File metadata and controls
44 lines (40 loc) · 1.09 KB
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
// This code finds the indices of two elements that sum up to the target.
#include <iostream>
#include <vector>
#include <unordered_set>
using std::cout;
using std::endl;
using std::vector;
bool TwoSum(const vector<int>& nums, int target, std::pair<int,int>& anspair)
{
bool pair = false;
std::unordered_set<int> fmap;
for(int i=0; i<nums.size(); i++)
{
if(fmap.find(nums[i])!=fmap.end())
{
pair = true;
anspair.first = target - nums[i];
anspair.second = nums[i];
break;
}
else
fmap.insert(target-nums[i]);
}
return pair;
}
void printNums(const vector<int>&& nums, int target)
{
std::pair<int,int> anspair;
bool result = TwoSum(nums, target, anspair);
if(result)
cout<<"the pair is : "<<anspair.first<<"\t"<<anspair.second<<endl;
else
cout<<"no pair found"<<endl;
}
int main()
{
vector<int> input = {1,5,7,8,9,15};
printNums({1,5,7,8,9,15},8);
return 0;
}