Skip to content

Commit 6230ec3

Browse files
authored
Merge pull request #2297 from yaxarat/kotlin
Match Kotlin solution for 973 to the video solution
2 parents 561a6bd + 4508924 commit 6230ec3

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed
Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,43 @@
1+
/**
2+
Solution using min heap
3+
*/
4+
class Solution {
5+
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
6+
val minHeap = PriorityQueue<IntArray> { a, b -> a[0] - b[0] }
7+
val result = Array<IntArray>(k) { IntArray(2) { 0 } }
8+
9+
for (point in points) {
10+
minHeap.add(
11+
intArrayOf(
12+
/* distance from (0,0) */ point[0].squared() + point[1].squared(),
13+
/* x coordinate */ point[0],
14+
/* y coordinate */ point[1]
15+
)
16+
)
17+
}
18+
19+
for (i in 0 until k) {
20+
val pointWithDistance = minHeap.poll()
21+
result[i][0] = pointWithDistance[1]
22+
result[i][1] = pointWithDistance[2]
23+
}
24+
25+
return result
26+
}
27+
28+
private fun Int.squared() = this * this
29+
}
30+
31+
/**
32+
Solution using built in sort function
33+
*/
134
class Solution {
235
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
336
val sorted = points.sortedBy{ it[0]*it[0] + it[1]*it[1]}
437
val list = arrayListOf<IntArray>()
5-
638
for (i in 0..k-1) {
739
list.add(sorted[i])
840
}
9-
1041
return list.toTypedArray()
1142
}
1243
}

0 commit comments

Comments
 (0)