描述
给定一些 points 和一个 origin,从 points 中找到 k 个离 origin 最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。
样例
例1:
输入: points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 3
输出: [[1,1],[2,5],[4,4]]
例2:
输入: points = [[0,0],[0,9]], origin = [3, 1], k = 1
输出: [[0,0]]
思考
根据到origin点的距离进行排序,取出前k个
代码
/**
* 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:
/**
* @param points: a list of points
* @param origin: a point
* @param k: An integer
* @return: the k closest points
*/
static bool cmp(const Point A, const Point B){
int x1 = A.x, x2 = B.x, y1 = A.y, y2 = B.y;
if (x1 * x1 +y1 * y1 < x2 * x2 + y2* y2)
return true;
else if (x1 * x1 + y1 * y1 > x2 * x2 + y2 * y2)
return false;
else
return x1 == x2 ? y1 < y2: x1 < x2;
}
vector<Point> kClosest(vector<Point> &points, Point &origin, int k) {
// write your code here
vector<Point> res;
if (k == 0) return res;
for (int i = 0; i < points.size();i++) {
points[i].x -= origin.x;
points[i].y -= origin.y;
}
sort(points.begin(), points.end(), cmp);
for (int i = 0; i < k; i++) {
points[i].x += origin.x;
points[i].y += origin.y;
res.push_back(points[i]);
}
return res;
}
};