Skip to content

Commit 51c9c76

Browse files
authored
Merge pull request #493 from shashank-556/fix
update Two_sum.cpp
2 parents a948df3 + 7f0b22d commit 51c9c76

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

Two_Sum.cpp

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
1-
// Two_Sum
21
/*
3-
Given an array of integers nums(sorted in ascending order) and an integer target,
2+
Given an array of integers and an integer target,
43
return indices(zero indexed) of the two numbers if exists such that they sum adds up to target.
54
*/
65
#include<bits/stdc++.h>
76
using namespace std;
87

98
vector<int> Two_Sum(vector<int> &arr, int target) {
109

11-
int low = 0, high = arr.size() - 1;
12-
while (low <= high) {
13-
int sum = arr[low] + arr[high];
14-
if (target == sum) {
15-
return {low, high};
16-
}
17-
else if (target < sum) {
18-
high--;
19-
}
20-
else {
21-
low++;
22-
}
23-
}
24-
return { -1, -1};
10+
std::unordered_map<int,int> mp;
11+
12+
for(int i=0;i<arr.size();i++){
13+
14+
if(mp.find(target-arr[i])!=mp.end())
15+
return {mp[target-arr[i]],i};
16+
17+
mp[arr[i]]=i;
18+
}
19+
20+
return {-1,-1};
2521
}
2622

2723
int main()
@@ -43,8 +39,8 @@ int main()
4339
vector<int> p = Two_Sum(arr, target);
4440

4541
if (p[0] == -1 && p[1] == -1)
46-
cout << "Two numbers not exist in array" << endl;
42+
cout << "Two numbers with sum "<<target<< " are not present in the array" << endl;
4743
else
4844
cout << "Indices are " << p[0] << " and " << p[1] << endl;
4945
return 0;
50-
}
46+
}

0 commit comments

Comments
 (0)