How to find k closest numbers of a given number from a given set of numbers
#include <bits/stdc++.h>
using namespace std;
int main()
{ int a[10]={6,8,10,54,7,9,1,4,3,18}; //take user input array of size n
int k=3; //no of closest element we want
int x=5; //no to which the required elements are close to
priority_queue <pair<int,int>>maxheap;
for(int i=0;i<10;i++)
{
maxheap.push( make_pair(abs(a[i]-x),a[i]));
if(maxheap.size()>k)
{
maxheap.pop();
}
}
while(maxheap.size()>0)
{
cout<<maxheap.top().second<<endl;
maxheap.pop();
}
return 0;
}
1 Comments
Last minute help before exam...Great content
ReplyDelete