-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2sum.cpp
More file actions
29 lines (25 loc) · 1.1 KB
/
2sum.cpp
File metadata and controls
29 lines (25 loc) · 1.1 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
/*Question:
2 Sum
Asked in:
Facebook
Amazon
Google
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based.
Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.
If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.
Input: [2, 7, 11, 15], target=9
Output: index1 = 1, index2 = 2 */
vector<int> Solution::twoSum(const vector<int> &A, int B) {
unordered_map<int,int> m;
for(int i=0;i<A.size();i++)
{
auto z=m.find(B-A[i]);
if(z!=m.end())
return (vector<int>{z->second,i+1});
auto p=m.find(A[i]);
if(p==m.end())
m[A[i]]=i+1;
}
return vector<int>{};
}