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; }};
阅读全文
0 0
- lintcode[612]:k个最近的点
- Lintcode-K个最近的点(#612)
- LintCode:M-K个最近的点
- LintCode K个最近的点
- LintCode: K个最近的点
- K个最近的点-LintCode
- 612. K个最近的点[LintCode]
- Lintcode 612. K个最近的点
- LintCode-[中等] 612. K个最近的点
- K个最近的点
- K个最近的点
- k个最近的点(Leetcode答案)
- 计算二维空间某点的最近k 个点
- 【K-D树 K维最近距离的t个点】HDU
- 在一个二维平面上找到离固定点最近的k个点位置
- m维空间里n个点每点最近的第k个点的距离
- 算法爱好者——K个最近的点 ? 待解决
- LintCode-第k个排列
- 多线程之重入锁ReentrantLock及原理
- Error:Execution failed for task ':app:processAnzhiDebugManifest'. > Manifest merger failed with mult
- Stroke and Brain
- MTK Android Driver :sensor
- PAT乙级(Basic)题库---1001
- lintcode[612]:k个最近的点
- 看深度学习框架排名第一的TensorFlow如何进行时序预测!
- Linux系统文件类型
- CAS服务集成
- Python shell之清屏
- objc_class 简介
- 前段判断是否验证后提交
- ios-自定义UITextFiled的属性设置
- CCF 历年真题之俄罗斯方块(_1604_2_Tetris.java)参考答案