Skip to content

Commit b562f75

Browse files
authored
Update 0658-find-k-closest-elements.kt (Optimization)
Added solution using binary search instead of linear. Both solutions are in the file.
1 parent 037a70d commit b562f75

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

kotlin/0658-find-k-closest-elements.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
/*
2+
* Optimized solution with binary search for the k-window instead of linear search. Time O(LogN-K) and Space O(1)
3+
*/
4+
class Solution {
5+
fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> {
6+
7+
var left = 0
8+
var right = arr.size - k
9+
10+
while (left < right) {
11+
val mid = (left + right) / 2
12+
if (x - arr[mid] > arr[mid + k] - x)
13+
left = mid + 1
14+
else
15+
right = mid
16+
}
17+
18+
val res = ArrayList<Int>()
19+
for(i in left until right+k) res.add(arr[i])
20+
return res
21+
}
22+
}
23+
124
/*
225
* Linear search with window resizing. Time: O(N-K) and Space O(1)
326
*/

0 commit comments

Comments
 (0)