K个最近的点

题目描述:给定一些 points 和一个 origin,从 points 中找到 k 个离 origin 最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。


Example

给出 points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 3
返回 [[1,1],[2,5],[4,4]]

思路:调用STL自带算法void sort(RandomAccessIterator beg,RandomAccessIterator end,BinaryPredicate op)对结构体struct Point进行排序,

      其中最重要的怎样设计op这个函数;op函数主要根据题目描述设计,完整代码如下:

#include <iostream>
#include<algorithm>
using namespace std;

struct Point
{
    int x;
    int y;
    Point():x(0),y(0) {}
    Point(int a,int b) : x(a),y(b) {}
};

static Point c(0,0);//设置全局变量,用来存储origin
class Solution
{
public:

    vector<Point> kClosest(vector<Point> points,Point origin,int k);

};


double distance(Point a,Point b)
{
   return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

bool less_distance(Point a,Point b)//op设计
{
    double d1 = distance(a,c);
    double d2 = distance(b,c);
    if(d1 <  d2)
        return true;
    else if(d1 == d2)
    {
        if(a.x < b.x)
            return true;
        else if(a.x == b.x)
        {
            if(a.y < b.y)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    else
        return false;
}

vector<Point> Solution::kClosest(vector<Point> points,Point origin,int k)
{
        c.x = origin.x;
        c.y = origin.y;//更新origin点坐标
        vector<Point> Result;
        Result.clear();
        sort(points.begin(),points.end(),less_distance);
        for(int i=0;i<k;i++)
        {
           Result.push_back(points[i]);
        }

       return Result;
}

int main()//测试代码
{
   vector<Point> points = {Point(4,6),Point(4,7),Point(4,4),Point(2,5),Point(1,1)};
   Point c(0,0);
   Solution m;
   vector<Point> Result;
   Result = m.kClosest(points,c,3);
   for(int i=0;i<3;i++)
   {
       cout << Result[i].x << "," << Result[i].y << endl;
   }
    cout << endl;
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值