Leetcode 1014 Solution

This article provides solution to leetcode question 1014 (k-closest-points-to-origin)

https://leetcode.com/problems/k-closest-points-to-origin

Solution

class Solution {
public:
    vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
        vector<vector<int>> res;
        map<int, int> m;

        for (int i = 0; i < points.size(); i++)
        {
            int dist = points[i][0] * points[i][0] + points[i][1] * points[i][1];
            m[dist] = i;
        }

        for (auto it = m.begin(); it != m.end(); it++)
        {
            if (res.size() >= K)
                break;

            res.push_back(points[it->second]);
        }

        return res;
    }
};