K个最近的点
Posted ssdut_yrp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]]
//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
/**
* @param points a list of points
* @param origin a point
* @param k an integer
* @return the k closest points
*/
@SuppressWarnings("null")
public static Point[] kClosest(Point[] points, Point origin, int k)
Point[] outputPoints = new Point[k];
for(int i=0;i<points.length;i++)
for (int j=i;j<points.length;j++)
if(length(points[i],origin)>length(points[j],origin))
Point temp=points[i];
points[i]=points[j];
points[j]=temp;
else if(length(points[i],origin)==length(points[j],origin))
if(points[i].x>points[j].x)
Point temp=points[i];
points[i]=points[j];
points[j]=temp;
else if(points[i].y>points[j].y)
Point temp=points[i];
points[i]=points[j];
points[j]=temp;
for (int i=0;i<k;i++)
outputPoints[i]=points[i];
return outputPoints;
//小到大
public void bubbleSort(int[] unsorted)
for (int i=0;i<unsorted.length;i++)
for (int j=i;j<unsorted.length;i++)
if(unsorted[i]>unsorted[j])
int temp=unsorted[i];
unsorted[i]=unsorted[j];
unsorted[j]=temp;
public static double length(Point start,Point end)
int temp_x=Math.abs(start.x-end.x);
int temp_y=Math.abs(start.y-end.y);
return Math.sqrt(temp_x*temp_x+temp_y*temp_y);
public static void print(Point pp)
System.out.println("最近的点:("+pp.x+","+pp.y+")");
/**
* @param args
*/
public static void main(String[] args)
// TODO Auto-generated method stub
Point[] p= new Point(4,6),new Point(4,7),new Point(4,4),new Point(2,5),new Point(1,1);
Point origin = new Point(0,0);
int k=3;
Point[] pNew = kClosest(p, origin, k);
for(int i=0;i<pNew.length;i++)
print(pNew[i]);
以上是关于K个最近的点的主要内容,如果未能解决你的问题,请参考以下文章