File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
Formation/21_Days_Challenge/Day_18_K_Closest_Points Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments