lintcode[612]:k个最近的点

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

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

思路:想法并不难,遍历数组找到距离的一个排序即可,主要想使用一下数据结构multiset,以及set的自定义排序规则。

参考代码:

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    /**
     * @param points a list of points
     * @param origin a point
     * @param k an integer
     * @return the k closest points
     */
    struct mycomp
    {
        bool operator () (const Point &a, const Point &b) const
        {
            if(a.x * a.x + a.y * a.y == b.x * b.x + b.y * b.y){
                if(a.x == b.x){
                    return a.y < b.y;
                }
                return a.x < b.x;
            }
            return a.x * a.x + a.y * a.y < b.x * b.x + b.y * b.y;
        }
    };
    vector<Point> kClosest(vector<Point>& points, Point& origin, int k) {
        // Write your code here
        multiset<Point, mycomp> set_;
        vector<Point> ans;
        int len = points.size();
        for(int i = 0; i < len; i ++){
            points[i].x -= origin.x;
            points[i].y -= origin.y;
            set_.insert(points[i]);
        }
        multiset<Point, mycomp>::iterator itor = set_.begin();
        for(int i = 0; i < k; i ++){
            Point p ((*itor).x + origin.x, (*itor).y + origin.y);
            ans.push_back(p);
            itor++;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值