File tree Expand file tree Collapse file tree 1 file changed +33
-2
lines changed Expand file tree Collapse file tree 1 file changed +33
-2
lines changed Original file line number Diff line number Diff line change
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
+ */
1
34
class Solution {
2
35
fun kClosest (points : Array <IntArray >, k : Int ): Array <IntArray > {
3
36
val sorted = points.sortedBy{ it[0 ]* it[0 ] + it[1 ]* it[1 ]}
4
37
val list = arrayListOf<IntArray >()
5
-
6
38
for (i in 0 .. k- 1 ) {
7
39
list.add(sorted[i])
8
40
}
9
-
10
41
return list.toTypedArray()
11
42
}
12
43
}
You can’t perform that action at this time.
0 commit comments