File tree Expand file tree Collapse file tree 1 file changed +14
-18
lines changed Expand file tree Collapse file tree 1 file changed +14
-18
lines changed Original file line number Diff line number Diff line change 1
- // Two_Sum
2
1
/*
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,
4
3
return indices(zero indexed) of the two numbers if exists such that they sum adds up to target.
5
4
*/
6
5
#include < bits/stdc++.h>
7
6
using namespace std ;
8
7
9
8
vector<int > Two_Sum (vector<int > &arr, int target) {
10
9
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 };
25
21
}
26
22
27
23
int main ()
@@ -43,8 +39,8 @@ int main()
43
39
vector<int > p = Two_Sum (arr, target);
44
40
45
41
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;
47
43
else
48
44
cout << " Indices are " << p[0 ] << " and " << p[1 ] << endl;
49
45
return 0 ;
50
- }
46
+ }
You can’t perform that action at this time.
0 commit comments