Amazon Interview Question
Software Engineer in Testsvoid pairofsums(int *d,int length)
{
int pair1=0,pair2=0;
vector<int>vector1;
map<int,int>possibilites;
for(int x=0;x<length;x++)
{
vector1.push_back(d[x]);
}
for(int i=0;i<vector1.size();i++)
{
cout<<vector1[i]<<endl;
for(int f=0;f<vector1.size();f++)
{
if((vector1[i]+d[f])==2)
{
pair1=vector1[i];
pair2=d[f];
possibilites[pair1]=pair2;
}
}
}
map<int,int>::iterator iter;
for(iter=possibilites.begin();iter!=possibilites.end();iter++)
{
cout<<"Pair 1: "<<iter->first<<" Pair 2: "<<iter->second<<endl;
}
}
first sort the array in nlgn and then its easy just take two pointers one pointing ats start index of array and one at the end of the array and start checking sum
- geeks July 27, 2011like this
whwrw a is the integer array givcen
int *p;
int *q;
p=a;
q=a+n-1;
while(p!=q)
{
if(*p+*q==sum)
{printf("(%d,%d)\n",*p,*q);
p++;
q--;
continue;}
if(*p+*q<sum)
{
p++;
continue;
}
q--;
}