Heap

class Solution {
public:
    vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
        priority_queue<pair<double, pair<int, int>>, 
            vector<pair<double, pair<int, int>>>, 
            greater<>> pq;
        for (auto p : points) {
            double d = sqrt(pow(p[0], 2) + pow(p[1], 2));
            pq.push({d, {p[0], p[1]}});
        }
        vector<vector<int>> results;
        while (k > 0 && pq.size()) {
            k--;
            results.push_back({pq.top().second.first, pq.top().second.second});
            pq.pop();
        }
        return results;
    }
};

TODO

TODO

Last updated

Was this helpful?