您的位置:首页 > 其它

在一个二维平面上找到离固定点最近的k个点位置

2017-10-23 18:19 330 查看

问题描述

/*

* 给定一些 points 和一个 origin, 从points中找出k个离origin最近的点,按照距离从小到大返回

* 如果有两个点有相同距离,按照x值进行排序,如果x值相等,按照y值进行排序

*

* 如果是静态数据,数据量不是特别多的话,直接做个排序就可以了

* 如果是动态数据的话,维护一个最小堆

*/

代码

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <queue>

typedef std::pair<int, int> P;

struct LessCmp {
bool reverse;
LessCmp(bool reverse = false): reverse(reverse) {}
bool operator()(P &a, P &b) {
bool res;
double dis1 = a.first * a.first + a.second * a.second,
dis2 = b.first * b.first + b.second * b.second;
if (fabs(dis1 - dis2) < 1e-6) {
if (a.first == b.first)
res = a.second < b.second;
else
res = a.first < b.first;
}
else
res = dis1 < dis2;
return reverse ? (!res) : res;
}
};

/**
* 直接排序
*/
class Solution1 {
public:
std::vector<P> getKNearest(std::vector<P> &points, P origin, int k)
{
// 坐标点进行归一化
for (auto &e : points) {
e.first -= origin.first;
e.second -= origin.second
9b9e
;
}
std::sort(points.begin(), points.end(), LessCmp());
if (points.begin() + k >= points.end())
return std::vector<P>(points);
return std::vector<P>(points.begin(), points.begin() + k);
}
};

// 使用最小堆
class Solution2 {
public:
std::vector<P> getKNearest(std::vector<P> &points, P origin, int k)
{
typedef std::priority_queue<P, std::vector<P>, LessCmp> Pq_t;
Pq_t pq(true);
for (auto &e: points) {
e.first -= origin.first;
e.second -= origin.second;
pq.push(e);
}
std::vector<P> res;
for (int i = 0; i < k && !pq.empty(); ++i) {
res.push_back(pq.top());
pq.pop();
}
return res;
}
};

int main()
{
int x[][2] = {{4, 6}, {4, 7}, {4, 4}, {2, 5}, {1, 1}};
std::vector<P> points;
for (int i = 0; i < sizeof(x)/sizeof(x[0]); ++i) {
points.push_back(P(x[i][0], x[i][1]));
}
P origin(0, 0);
int k = 3;

//    std::vector<P> ret = Solution1().getKNearest(points, origin, k);
std::vector<P> ret = Solution2().getKNearest(points, origin, k);

for (auto &e : ret)
std::cout << "(" << e.first << ", " << e.second << ") " << std::endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐