612. K个最近的点[LintCode]
来源:互联网 发布:软件销售企业财务处理 编辑:程序博客网 时间:2024/06/08 09:13
题目
给定一些 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]]
代码
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */public class Solution { public static void main(String[] args) { int k = 3; Point[] result = new Point[k]; Point origin = new Point(0, 0); Point[] points = { new Point(4, 6), new Point(4, 7), new Point(4, 4), new Point(2, 5), new Point(1, 1) }; result = kClosest(points, origin, k); for (Point p : result) { System.out.println("[" + p.x + "," + p.y + "]"); } } public Point[] kClosest(Point[] points, Point origin, int k) { Point[] result = new Point[k]; Point tmpPoint = new Point(); for (int i = 0; i < points.length; i++) { for (int j = i; j < points.length; j++) { //比较点和origin点的距离,若前面的点的距离大于后面点的距离,则交换两个点的位置 if (calcLength(points[i], origin) > calcLength(points[j], origin)) { tmpPoint = points[i]; points[i] = points[j]; points[j] = tmpPoint; }//如果两个点有相同距离,则按照x值来排序 else if (calcLength(points[i], origin) == calcLength( points[j], origin)) { if (points[i].x > points[j].x) { tmpPoint = points[i]; points[i] = points[j]; points[j] = tmpPoint; }//若x值相同,按照y值排序。 else if (points[i].x == points[j].x) { if (points[i].y == points[j].y) { tmpPoint = points[i]; points[i] = points[j]; points[j] = tmpPoint; } } } } } //输出符合条件的前k的点 for (int i = 0; i < k; i++) { result[i] = points[i]; } return result; } //计算两点间距离 public static double calcLength(Point point, Point origin) { double length = Math.sqrt((point.x - origin.x) * (point.x - origin.x) + (point.y - origin.y) * (point.y - origin.y)); return length; }}
阅读全文
0 0
- 612. K个最近的点[LintCode]
- Lintcode 612. K个最近的点
- lintcode[612]:k个最近的点
- Lintcode-K个最近的点(#612)
- LintCode:M-K个最近的点
- LintCode K个最近的点
- LintCode: K个最近的点
- K个最近的点-LintCode
- LintCode-[中等] 612. K个最近的点
- K个最近的点
- K个最近的点
- k个最近的点(Leetcode答案)
- 计算二维空间某点的最近k 个点
- 【K-D树 K维最近距离的t个点】HDU
- 在一个二维平面上找到离固定点最近的k个点位置
- m维空间里n个点每点最近的第k个点的距离
- 算法爱好者——K个最近的点 ? 待解决
- LintCode-第k个排列
- Jlink 命令【常用命令】
- spark windows开发调试环境
- OpenResty(Nginx+Lua)开发入门
- 深入理解计算机系统(第三版) 第二章答案(仅供参考!)
- Linux文件管理
- 612. K个最近的点[LintCode]
- [uboot] uboot启动kernel篇(三)——uboot解析uImage的kernel信息
- vue使用图表类2 柱形图表
- 一道凑数问题
- Spring是如何加载Xml文件的
- Conllection之LinkedList源码简析
- 创建maven web项目 pom报错:Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war
- BZOJ2588 主席树
- C语言实验——余弦