/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:

    struct compare {
        bool operator() (Point& l, Point& r) {
            if (l.a )
        }
    }
    // Find the points with shortest distance to origin, use a max heap to keep tracking current point in heap that is most far away from origin so that the new point may or may not replace it;
    struct compare{
        bool operator()(const pair<Point, int>& l, const pair<Point, int>& r) {
            if (l.second != r.second) {
                return l.second < r.second;
            } else {
                // Sort by x-axis or by y-axis means that when distance to origin is the same, the point with larger x or y axis stays closer to the top of the heap;
                if (l.first.x != r.first.x) {
                    return l.first.x < r.first.x;
                } else {
                    return l.first.y < r.first.y;
                }
            }
        }
    };

    vector<Point> kClosest(vector<Point>& points, Point& origin, int k) {
        // Write your code here
        vector<Point> results;
        int size = points.size();
        if (size == 0) {
            return results;
        }

        priority_queue<pair<Point, int>, vector<pair<Point, int>>, compare> pQ;

        for (int i = 0; i < size; i++) {
            Point cur = points[i];
            int dist = (cur.x - origin.x) * (cur.x - origin.x) + (cur.y - origin.y) * (cur.y - origin.y);
            if (pQ.size() < k) {
                pQ.push(make_pair(cur, dist));
            } else {
                pQ.push(make_pair(cur, dist));
                pQ.pop();
            }
        }

        while (!pQ.empty()) {
            pair<Point, int> front = pQ.top();
            pQ.pop();
            results.push_back(front.first);
        }

        int left = 0;
        int right = results.size() - 1;

        while (left < right) {
            Point tmp = results[left];
            results[left] = results[right];
            results[right] = tmp;
            left++;
            right--;
        }

        return results;
    }
};

results matching ""

    No results matching ""