Advertisement
imashutosh51

K closest points to origin

Jul 23rd, 2022 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #define pv pair<int,pair<int,int>>
  2. class Solution {
  3. public:
  4.     vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
  5.       priority_queue<pv,vector<pv>,greater<pv>> pq;   //find distnace of all nodes from origin or other point if given as source
  6.       for(int i=0;i<points.size();i++){               //and push it into min heap along with it's cordinates
  7.          int a=points[i][0],b=points[i][1];
  8.          pq.push(make_pair(a*a+b*b,make_pair(a,b)));  
  9.       }
  10.       vector<vector<int>> res;
  11.       for(int i=0;i<k;i++){    //pop k cordinates from min_heap which will be closest to origin
  12.           pv temp=pq.top();
  13.           pq.pop();
  14.           vector <int> t;
  15.           t.push_back(temp.second.first);
  16.           t.push_back(temp.second.second);
  17.           res.push_back(t);
  18.           t.clear();
  19.       }
  20.         return res;
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement