Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3a75ffd

Browse files
authored
Update 0973-k-closest-points-to-origin.kt
1 parent6230ec3 commit3a75ffd

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
privatefun Int.squared()=this*this
2929
}
3030

31+
/**
32+
Solution using a max Heap
33+
*/
34+
classSolution {
35+
funkClosest(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(pointin 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(iin 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)

[8]ページ先頭

©2009-2025 Movatter.jp