File tree Expand file tree Collapse file tree 1 file changed +24
-1
lines changed Expand file tree Collapse file tree 1 file changed +24
-1
lines changed Original file line number Diff line number Diff line change @@ -28,6 +28,29 @@ class Solution {
28
28
private fun Int.squared () = this * this
29
29
}
30
30
31
+ /* *
32
+ Solution using a max Heap
33
+ */
34
+ class Solution {
35
+ fun kClosest (points : Array <IntArray >, k : Int ): Array <IntArray > {
36
+ val maxHeap = PriorityQueue <IntArray >{ e1, e2 -> e2[0 ] - e1[0 ] }
37
+ val res = Array (k){ IntArray (2 ) }
38
+ for (point in points){
39
+ val (x,y) = point
40
+ val distance = (x * x) + (y * y) // we don't need to sqrt since the actual length is of no use
41
+ maxHeap.add(intArrayOf(distance,x,y))
42
+ if (maxHeap.size > k) // keep only the K closest distances
43
+ maxHeap.poll()
44
+ }
45
+
46
+ for (i in res.indices){
47
+ val (d,x,y) = maxHeap.poll()
48
+ res[i] = intArrayOf(x,y)
49
+ }
50
+ return res
51
+ }
52
+ }
53
+
31
54
/* *
32
55
Solution using built in sort function
33
56
*/
@@ -40,4 +63,4 @@ class Solution {
40
63
}
41
64
return list.toTypedArray()
42
65
}
43
- }
66
+ }
You can’t perform that action at this time.
0 commit comments