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

Commit6230ec3

Browse files
authored
Merge pull requestneetcode-gh#2297 from yaxarat/kotlin
Match Kotlin solution for 973 to the video solution
2 parents561a6bd +4508924 commit6230ec3

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+
classSolution {
5+
funkClosest(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 (pointin 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 (iin0 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+
privatefun Int.squared()=this*this
29+
}
30+
31+
/**
32+
Solution using built in sort function
33+
*/
134
classSolution {
235
funkClosest(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 (iin0..k-1) {
739
list.add(sorted[i])
840
}
9-
1041
return list.toTypedArray()
1142
}
1243
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp