Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them.
- The distance between two points on a plane is the Euclidean distance.
- You may return the answer in any order.
- Input format
- First line contains 2 integers N, K - Number of points and the integer K.
- Next N lines contain 2 integers x, y - The coordinates of the points.
- Output format
- Print K lines each containing the coordinates of the closest points.
- Sample Input 1
- 5 3
- 1 0
- -4 2
- 2 -3
- 3 5
- 0 2
- Sample Output 1
- 1 0
- 2 -3
- 0 2
- Explanation
- Distances of points are:
- Point (1,0) = sqrt(1)
- Point (-4,2) = sqrt(20)
- Point (2,-3) = sqrt(13)
- Point (3,5) = sqrt(34)
- Point (0,2) = sqrt(4)
- Points (1,0), (0,2) and (2,-3) have the least distance from the origin.
- Constraints
- 1 <= N <= 10^5
- 1 <= K <= N
- -10^6 <= Xi, Yi <= 10^6
- */
- unsigned long long getDistance(int x,int y){
- // unsigned long long distance=(x*x+y*y);
- long X=x;
- long Y=y;
- // long long distance = static_cast<long long>(x) * x + static_cast<long long>(y) * y;
- unsigned long long distance=(X*X+Y*Y);
- return distance;
- }
- struct comparator{
- bool operator()( pair<unsigned long long,pair<int,int>>& p1, pair<unsigned long long,pair<int,int>>& p2){
- return p1.first<p2.first;
- }
- };
- vector<vector<int>> kClosestPointsToOrigin(vector<vector<int>> points, int k){
- vector<vector<int>> ans;
- priority_queue< pair<unsigned long long,pair<int,int>> ,
- vector< pair<unsigned long long,pair<int,int>> >,
- comparator
- >pq;
- unsigned long long len=points.size();
- for(int i=0;i<len;i++){
- int x=points[i][0];
- int y=points[i][1];
- pair<int,int>p={x,y};
- unsigned long long distance=getDistance(x,y);
- pq.push({distance,p});
- if(pq.size()>k)
- pq.pop();
- }
- while(!pq.empty()){
- auto tmp=pq.top();
- vector<int>currentPoint={tmp.second.first,tmp.second.second};
- ans.push_back(currentPoint);
- pq.pop();
- }
- return ans;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement