We have a list of points
on the plane. Find the K
closest points to the origin (0, 0)
.
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
Example 1:
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)
Note:
1 <= K <= points.length <= 10000
-10000 < points[i][0] < 10000
-10000 < points[i][1] < 10000
這道題給了平面上的一系列的點,讓求最接近原點的K個點。基本上沒有什么難度,無非就是要知道點與點之間的距離該如何求。一種比較直接的方法就是給這個二維數組排序,自定義排序方法,按照離原點的距離從小到大排序,注意這里我們並不需要求出具體的距離值,只要知道互相的大小關系即可,所以並不需要開方。排好序之后,返回前k個點即可,參見代碼如下:
解法一:
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
sort(points.begin(), points.end(), [](vector<int>& a, vector<int>& b) {
return a[0] * a[0] + a[1] * a[1] < b[0] * b[0] + b[1] * b[1];
});
return vector<vector<int>>(points.begin(), points.begin() + K);
}
};
下面這種解法是使用最大堆 Max Heap 來做的,在 C++ 中就是用優先隊列來做,這里維護一個大小為k的最大堆,里面放一個 pair 對兒,由距離原點的距離,和該點在原數組中的下標組成,這樣優先隊列就可以按照到原點的距離排隊了,距離大的就在隊首。這樣每當個數超過k個了之后,就將隊首的元素移除即可,最后把剩下的k個點存入結果 res 中即可,參見代碼如下:
解法二:
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
vector<vector<int>> res;
priority_queue<pair<int, int>> pq;
for (int i = 0; i < points.size(); ++i) {
int t = points[i][0] * points[i][0] + points[i][1] * points[i][1];
pq.push({t, i});
if (pq.size() > K) pq.pop();
}
while (!pq.empty()) {
auto t = pq.top(); pq.pop();
res.push_back(points[t.second]);
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/973
類似題目:
Kth Largest Element in an Array
參考資料:
https://leetcode.com/problems/k-closest-points-to-origin/
https://leetcode.com/problems/k-closest-points-to-origin/discuss/217999/JavaC%2B%2BPython-O(N)