Interview Question

Interview Question

Postby ImplicitScheme » Tue Jan 04, 2011 7:25 am

I got this question in an interview and it gave me trouble. Anybody know an efficient way to do it ?



Write a function to find three numbers in an array which sum to zero.



Another question was



Sort a list of numbers in which each number is at a distance k from its actual position
ImplicitScheme
 
Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

Postby Cuchulainn » Thu Jan 13, 2011 11:58 pm

what was your reply/soution?
User avatar
Cuchulainn
 
Posts: 669
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Postby ImplicitScheme » Sun Jan 23, 2011 10:01 pm

For this problem

"

Sort a list of numbers in which each number is at a distance k from its actual position"



It seems this situation can only occur if the list has an even number of elements. I gave them a function like this.



void swap( vector<int>& v, int one, int two )

{

int temp1 = v[one] ;

v[one] =v[two] ;

v[two] = temp1 ;

} ;



void Koff(vector<int>& v, int k )

{



if((v.size())%2!=0 || k>2)

{

cout<< "FAILURE" ;

}







if(k==1)

for(int j = 0 ; j<v.size() -1 ; j=j+2)



swap(v,j,j+1) ;







if(k==2 && v.size()%4==0)

for(int j=0 ; j<v.size() -2; j++)

{

swap(v,j,j+2) ;

} ;

};





I'm not sure if I caught every possible case in there. I'm just curious if there is a better approach than this.
ImplicitScheme
 
Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm


Return to C++

Who is online

Users browsing this forum: No registered users and 2 guests

cron