#include <vector>
#include <iostream>
#include <string>
#include <c++/algorithm>
#include <c++/map>
using namespace std;
struct Coord{
int x;
int y;
};
vector<Coord> kClosest(vector<Coord>& points, Coord e, int K) {
vector<Coord> res;
map<int,Coord,less_equal<int>> m;
for(int i=0;i<points.size();i++){
int dis=pow((points[i].x-e.x),2)+pow((points[i].y-e.y),2); //KEY为距离,VALUE为坐标
m[dis]=points[i];
}
for (auto it = m.begin(); it != m.end(); ++it) {
if (K==0)
break;
K--;
res.push_back(it->second);
}
return res;
}
int main(){
Coord e ={0,0};
Coord p1 ={2,3};
Coord p2 ={4,5};
Coord p3 ={1,1};
Coord p4 ={-1,-1};
vector<Coord> points;
points.push_back(p1);
points.push_back(p2);
points.push_back(p3);
points.push_back(p4);
const vector<Coord> &vector = kClosest(points, e, 2);
for (int i = 0; i < vector.size(); ++i) {
cout<<vector[i].x<<" "<<vector[i].y<<endl;
}
return 0;
}
T2
最新推荐文章于 2025-02-17 23:22:12 发布