Skip to content

Commit d40d1bc

Browse files
author
Bogdan Hladiuc
committed
Day 18 K Closest Points
1 parent 6622af8 commit d40d1bc

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+

2+
#nullable disable warnings
3+
namespace Formation {
4+
5+
public class KClosestPoints {
6+
public static void Run() {
7+
var points = new Point[] {
8+
new Point {
9+
X = 2,
10+
Y = 0
11+
},
12+
new Point {
13+
X = 0,
14+
Y = 2
15+
},
16+
new Point {
17+
X = 3,
18+
Y = 3
19+
},
20+
new Point {
21+
X = 4,
22+
Y = 2
23+
},
24+
new Point {
25+
X = 2,
26+
Y = 5
27+
}
28+
};
29+
var K = 3;
30+
31+
var result = Solution(points, K);
32+
33+
if (result == null) {
34+
return;
35+
}
36+
37+
foreach (var point in result) {
38+
Console.WriteLine($"({point.X}, {point.Y})");
39+
}
40+
}
41+
42+
private static Point[] Solution(Point[] points, int K) {
43+
if (points.Length < K) {
44+
return null;
45+
}
46+
47+
var pq = new PriorityQueue<Point, double>(Comparer<double>.Create((x, y) => y.CompareTo(x)));
48+
49+
foreach (var point in points) {
50+
pq.Enqueue(point, point.Dist);
51+
52+
while (pq.Count > K) {
53+
pq.Dequeue();
54+
}
55+
}
56+
57+
return pq.UnorderedItems.Select(item => item.Element).ToArray();
58+
}
59+
60+
private class Point {
61+
public int X { get; set; }
62+
public int Y { get; set; }
63+
64+
public double Dist {
65+
get {
66+
return Math.Sqrt(this.X * this.X + this.Y * this.Y);
67+
}
68+
}
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)