Skip to content

Commit 3a75ffd

Browse files
authored
Update 0973-k-closest-points-to-origin.kt
1 parent 6230ec3 commit 3a75ffd

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

kotlin/0973-k-closest-points-to-origin.kt

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,29 @@ class Solution {
2828
private fun Int.squared() = this * this
2929
}
3030

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+
3154
/**
3255
Solution using built in sort function
3356
*/
@@ -40,4 +63,4 @@ class Solution {
4063
}
4164
return list.toTypedArray()
4265
}
43-
}
66+
}

0 commit comments

Comments
 (0)