LintCode K个最近的点
来源:互联网 发布:服装数据分析软件 编辑:程序博客网 时间:2024/06/08 02:16
题目
给定一些 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]]
坐标点类
class Point { int x; int y; Point() { x = 0; y = 0; } Point(int a, int b) { x = a; y = b; } @Override public String toString() { return "[" + x + "," + y + "]"; }}
思路
- 计算距离^2,获得与点等长的数组,切距离与点的坐标一一对应。
- 循环k次,寻找k个最小距离,按照最小距离的下标,并记录最近距离点。
- 每次比较,都要交换距离调整和点在数组中的位置,防止丢失与重复。
代码
public static Point[] kClosest(Point[] points, Point origin, int k) { // Write your code here int[] distance = new int[points.length]; //计算距离^2 for (int i = 0; i < points.length; i++) { distance[i] = (points[i].x - origin.x) * (points[i].x - origin.x) + (points[i].y - origin.y) * (points[i].y - origin.y); } Point[] ps = new Point[k]; //获取距离最近的k个坐标 for (int i = 0; i < k; i++) { int min = distance[i]; ps[i] = points[i]; for (int j = i + 1; j < distance.length; j++) { if (min > distance[j]) { min = distance[j]; //交换,调整对应距离值,防止重复 int t = distance[i]; distance[i] = distance[j]; distance[j] = t; ps[i] = points[j]; //交换,调整对应坐标,防止重复 Point o = points[j]; points[j] = points[i]; points[i] = o; } if (min == distance[j]) { if (points[i].x > points[j].x) { ps[i] = points[j]; //交换,调整对应坐标,防止重复 Point o = points[j]; points[j] = points[i]; points[i] = o; } else if (points[i].x == points[j].x) { if (points[i].y > points[j].y) { ps[i] = points[j]; //交换,调整对应坐标,防止重复 Point o = points[j]; points[j] = points[i]; points[i] = o; } } } } } return ps; }
阅读全文
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个排列
- 字符串左移
- RabbitMQ核心概念篇
- 剑指offer(纪念版) 面试题3:二维数组中的查找
- Github Pages搭建个人站点和项目站点
- Activiti之流程通过、驳回、会签、转办、中止、挂起等核心操作封装(Activiti5.9)
- LintCode K个最近的点
- 一些实用的网站
- 浏览器history对象
- soj3427: Dark roads_最小生成树Kruskal
- 常见数据库连接池的配置
- [转]bootstrap-table文件汇总
- python 面试
- Echars简单地图制作
- C++学习笔记【第一部分第七章:类】