【发布时间】:2017-06-29 07:34:50
【问题描述】:
最近在一次采访中被问到这个问题
public interface PointsOnAPlane {
/**
* Stores a given point in an internal data structure
*/
void addPoint(Point point);
/**
* For given 'center' point returns a subset of 'm' stored points that are
* closer to the center than others.
*
* E.g. Stored: (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
*
* findNearest(new Point(0, 0), 3) -> (0, 1), (0, 2), (0, 3)
*/
vector<Point> findNearest(vector<Point> points, Point center, int m);
}
这是我使用的以下方法
1) 创建一个最大堆priority_queue来存储最近的点
priority_queue<Point,vector<Point>,comp> pq;
2) 如果优先队列大小,则迭代点向量并推送一个点
3) 如果 size == m 则将队列顶部与当前点进行比较,并在必要时弹出
for(int i=0;i<points.size();i++)
{
if(pq.size() < m)
{
pq.push(points[i]);
}
else
{
if(compareDistance(points[i],pq.top(),center))
{
pq.pop();
pq.push(points[i]);
}
}
}
4) 最后将优先队列的内容放入一个vector中并返回。
我应该如何编写 comp 和 compareDistance 比较器,这将允许我最初存储 m 个点,然后将当前点与顶部的点进行比较?
【问题讨论】:
-
分享一个想法。我们可以使用像四叉树或网格这样的空间划分。所以当中心改变时,我们不需要resort points或重建priority_queue。
-
为什么需要优先队列? 1. 测量到所有点的距离。将距离点(或点索引)存储到向量中,2 partial_sort 这个向量 3. 复制点到结果
-
public interface ...你确定是 C++ 吗?
标签: c++ comparator priority-queue