题目描述:给定一些 points
和一个 origin
,从 points
中找到 k
个离 origin
最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。
Example
给出 points = [[4,6]
,[4,7],[4,4],
[2,5],[1,1]]
, origin = [0, 0]
, k = 3
返回 [[1,1],[2,5],[4,4]]
思路:调用STL自带算法void sort(RandomAccessIterator beg,RandomAccessIterator end,BinaryPredicate op)对结构体struct Point进行排序,
其中最重要的怎样设计op这个函数;op函数主要根据题目描述设计,完整代码如下:
#include <iostream>
#include<algorithm>
using namespace std;
struct Point
{
int x;
int y;
Point():x(0),y(0) {}
Point(int a,int b) : x(a),y(b) {}
};
static Point c(0,0);//设置全局变量,用来存储origin
class Solution
{
public:
vector<Point> kClosest(vector<Point> points,Point origin,int k);
};
double distance(Point a,Point b)
{
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
bool less_distance(Point a,Point b)//op设计
{
double d1 = distance(a,c);
double d2 = distance(b,c);
if(d1 < d2)
return true;
else if(d1 == d2)
{
if(a.x < b.x)
return true;
else if(a.x == b.x)
{
if(a.y < b.y)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
vector<Point> Solution::kClosest(vector<Point> points,Point origin,int k)
{
c.x = origin.x;
c.y = origin.y;//更新origin点坐标
vector<Point> Result;
Result.clear();
sort(points.begin(),points.end(),less_distance);
for(int i=0;i<k;i++)
{
Result.push_back(points[i]);
}
return Result;
}
int main()//测试代码
{
vector<Point> points = {Point(4,6),Point(4,7),Point(4,4),Point(2,5),Point(1,1)};
Point c(0,0);
Solution m;
vector<Point> Result;
Result = m.kClosest(points,c,3);
for(int i=0;i<3;i++)
{
cout << Result[i].x << "," << Result[i].y << endl;
}
cout << endl;
return 0;
}