用 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)

更新时间:2019 年 10 月 22 日

294 个浏览量

开启你的 职业生涯

通过完成课程获得相关证书

开始
广告