forked from xieqilu/Qilu-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path63.FindKClosestsPoints.java
More file actions
62 lines (56 loc) · 1.31 KB
/
Copy path63.FindKClosestsPoints.java
File metadata and controls
62 lines (56 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class Point
{
int x;
int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class PointwithDis
{
Point p;
int dis;
public PointwithDis(Point p, int d)
{
this.p = p;
this.dis = d;
}
}
public class Finder
{
public static Point[] getCloseK(Point[] points, Point origin, int k)
{
PriorityQueue<PointwithDis> kPoints = new PriorityQueue<PointwithDis>(K, new Comparator<PointwithDis>(){
public int compare(PointwithDis arg0, PointwithDis arg1) {
return (int) (arg1.dis - arg0.dis)
}
});
PointwithDis[] pointswithdis = new PointwithDis[points.length]; //create new array to store all points with dis
int index = 0;
for(Point p : points)
{
double dis = Match.abs((double)(origin.x -p.x)/(origin.y-p.y));
pointswithdis[index++] = new PointwithDis(p, dis);
}
for(PointwithDis p : pointswithdis)
{
if(kPoints.size() < k)
kPoints.offer(p);
else{
if(kPoints.peek().dis > p.dis){
kPoints.poll();
kPoints.offer(p);
}
}
}
Point[] result = new Point[K];
index = 0;
while(!kPoints.isEmpty())
{
result[index++] = kPoints.poll().p;
}
return result;
}
}