[LeetCode] K Closest Points to Origin

973. K Closest Points to Origin

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

1
2
3
4
5
6
7
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
sort(begin(points), end(points), [](const vector<int>& a, const vector<int>& b) { return a.front() * a.front() + a.back() * a.back() < b.front() * b.front() + b.back() * b.back(); });
return vector<vector<int>> (points.begin(), points.begin() + k);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/k-closest-points-to-origin/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.