Skip to content

Commit 7cdc2cf

Browse files
Merge pull request matthewsamuel95#262 from ashish4321/master
Added 2_sums in Hashish folder
2 parents 9a1f387 + 4c0b243 commit 7cdc2cf

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Hashing/2_Sum/2_Sum._ashish4321.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
typedef long long ll;
4+
5+
struct node
6+
{
7+
ll val;
8+
ll pos;
9+
};
10+
11+
bool cmp(node a, node b)
12+
{
13+
return (a.val<b.val);
14+
}
15+
16+
int main(void)
17+
{
18+
// Input number of elements of array
19+
ll n;
20+
cin>>n;
21+
// Initialize the struct for n elements
22+
node nums[n];
23+
ll a;
24+
for(ll i=0;i<n;i++)
25+
{
26+
cin>>a;
27+
nums[i].val=a;
28+
nums[i].pos=i;
29+
}
30+
// sort the struct according to val
31+
sort(nums,nums+n,cmp);
32+
// Input target sum required
33+
ll target;
34+
cin>>target;
35+
// To find two indices of array whose sum is target
36+
ll low=0;
37+
ll high=n-1;
38+
ll sum=INT_MIN;
39+
while(sum!=target)
40+
{
41+
sum=(nums[low].val+nums[high].val);
42+
if(sum>target)
43+
{
44+
high--;
45+
}
46+
else if(sum<target)
47+
{
48+
low++;
49+
}
50+
else
51+
{
52+
break;
53+
}
54+
}
55+
cout<<nums[low].pos<<" "<<nums[high].pos;
56+
return 0;
57+
}

0 commit comments

Comments
 (0)