在C ++中找到K个最接近原点的点
假设我们有一组要点。我们的任务是找到最接近原点的K个点。假设点是(3,3),(5,-1)和(-2,4)。然后最接近的两个(K=2)点是(3,3),(-2,4)。
为了解决这个问题,我们将基于点的欧几里得距离对列表进行排序,然后从排序的列表中获取最上面的K个元素。这些是K最近的点。
示例
#include<iostream> #include<algorithm> using namespace std; class Point{ private: int x, y; public: Point(int x = 0, int y = 0){ this->x = x; this->y = y; } void display(){ cout << "("<<x<<", "<<y<<")"; } friend bool comparePoints(Point &p1, Point &p2); }; bool comparePoints(Point &p1, Point &p2){ float dist1 = (p1.x * p1.x) + (p1.y * p1.y); float dist2 = (p2.x * p2.x) + (p2.y * p2.y); return dist1 < dist2; } void closestKPoints(Point points[], int n, int k){ sort(points, points+n, comparePoints); for(int i = 0; i<k; i++){ points[i].display(); cout << endl; } } int main() { Point points[] = {{3, 3},{5, -1},{-2, 4}}; int n = sizeof(points)/sizeof(points[0]); int k = 2; closestKPoints(points, n, k); }
输出结果
(3, 3) (-2, 4)