-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay8.cpp
More file actions
43 lines (33 loc) · 809 Bytes
/
Day8.cpp
File metadata and controls
43 lines (33 loc) · 809 Bytes
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
/*
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
*/
#include <bits/stdc++.h>
using namespace std;
bool twoSum(vector<int> &arr, int sum)
{
int n = arr.size();
unordered_set<int> targetSum(n);
for (int i = 0; i < n; i++)
{
int diff = sum - arr[i];
if (!targetSum.count(arr[i]))
{
targetSum.insert(diff);
}
else
{
return true;
}
}
return false;
}
int main()
{
vector<int> arr = {10, 15, 3, 7};
int k = 17;
cout << (twoSum(arr, k) ? "true" : "false") << endl;
return 0;
}