Skip to content

Commit 6f2c6c6

Browse files
authored
Add files via upload
1 parent c5ef838 commit 6f2c6c6

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

Array/27 Find a pair with sum k.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include<iostream>
2+
using namespace std;
3+
int main ()
4+
{
5+
int A[10]={1,2,4,5,6,8,10,12,14,15};
6+
int n =sizeof(A)/sizeof(int);
7+
int k=10 ;// sum of pair of element is 10
8+
int i,j;
9+
i=0;
10+
j=n-1;
11+
while (i<j)
12+
{
13+
14+
if (A[i]+A[j]==k)
15+
{
16+
cout<<A[i] <<"+"<<A[j]<<"="<<k<<endl;
17+
i++;
18+
j--;
19+
}
20+
else if (A[i]+A[j]<k)
21+
{
22+
i++;
23+
} // increment i if the sum of two element is less than k
24+
else
25+
j--;//decremnt j if the sum of two elements is greater than k
26+
}
27+
28+
cout<<endl;
29+
return 0;
30+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#include<iostream>
2+
using namespace std ;
3+
int main ()
4+
{
5+
int i,j;
6+
int A[10]={2,3,1,8,6,7,9,1,5,4};
7+
int k=10;
8+
int n=sizeof(A)/sizeof(int);
9+
10+
for (i=0;i<n;i++)
11+
{
12+
for (j=i+1;j<n;j++)
13+
{
14+
if (A[i]+A[j]==k)
15+
cout <<A[i]<<"+"<<A[j]<<"="<<k<<endl;
16+
}
17+
}
18+
return 0;
19+
}
20+
// time complexity is o(n^2)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#include<iostream>
2+
using namespace std;
3+
int main ()
4+
{
5+
int A[10]={1,6,2,4,5,10,11,12,3,7};
6+
int k=10;
7+
int H[20]={0}; // Initialize the size of hashing array with the largest element in array A ;
8+
int n= sizeof(A)/sizeof(int);
9+
10+
for (int i=0;i<n;i++)
11+
{
12+
if (H[k-A[i]]!=0 && k-A[i]>=0 )
13+
cout<<A[i]<<"+"<<k-A[i]<<"="<<k<<endl;
14+
H[A[i]]++;
15+
16+
}
17+
return 0;
18+
}

0 commit comments

Comments
 (0)