two pointer technique which is used to solve some basic algorithms related question like 2sum, 3sum, and difference of 2 item in a vector equal to given target
the two-pointer technique is a very popular technique to solve some basic problem like
just watch this nice video for more information
https://www.youtube.com/watch?v=2wVjt3yhGwg&t=174s
https://leetcode.com/articles/two-pointer-technique/
1. Given a vector of integers and a target sum returns true if any two elements sum is equal to the target in the given vector
bool checkSum(int sum, vector<int> &myVect)
{
sort(myVect.begin(),myVect.end());
int i=0,j=myVect.size()-1;
while(j>=i)
{
if(myVect[i]+myVect[j]==sum)
{
return true;
}else if(myVect[i]+myVect[j]>sum)
{
j--;
}else if(myVect[j]+myVect[i]<sum)
{
i++;
}
}
return false;
}
2. Given a vector of integers and a target difference returns true if any two elements dfference in vector is equal to the target in the given vector.
bool checkDiff(int dif,vector<int> &myVect)
{
sort(myVect.begin(),myVect.end());
int i=0;
int j=1;
int size=myVect.size()-1;
while(i<=size && j<=size)
{
if(myVect[j]-myVect[i]==dif)
{
return true;
}else if(myVect[j]-myVect[i]<dif)
{
j++;
}else if(myVect[j]-myVect[i]>dif)
{
i++;
}
}
return false;
}
working sample
https://www.onlinegdb.com/edit/HJooqlZLP
Comments
Post a Comment