lintcode[612]:k个最近的点

来源:互联网 发布:ubuntu 界面小应用 编辑:程序博客网 时间:2024/05/20 16:00

给定一些 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;    }};
原创粉丝点击