We are given a vector and integer as follows:
vector<int> numbers
int k
find the count of pairs in numbers that have the diference k.
For example,
numbers = [1,1,2,2,3,3] and
k = 1
thus the ordered pairs will be (1,2) and (2,3) and the count will be 2.
numbers = [1,2,3,4,5,6]
k = 2
thus the ordered pairs will be (1,3), (2,4), (3,5), (4,6) and the count will be 4.
In case no such pair is possible the count needs to be zero and the function will return the count in all cases.
- No negative values are allowed.
- In the pair (x,y), x < y.
For the above question, I have successfully written a O(n^2) solution:
int numberofPairs(vector<int>numbers, int k)
{
int count = 0;
set<int> s1;
vector<int>::iterator i;
set<int>::iterator j;
set<int>::iterator z;
for(i = numbers.begin(); i!-numbers.end(); i++)
s1.insert(*i);
for(j = s1.begin(); j!=s1.end(); j++)
{ for(z = s1.begin(); z!=s1.end(); z++)
{ if((*j + k) == z)
{
count++;
break;
}
}
}
return count;
}
Is there any way possible to solve it with more efficient solution?