Skip to content

Commit 3b15418

Browse files
authored
Merge pull request #3156 from chojs23/main
Create 0658-find-k-closest-elements.rs
2 parents edae907 + 2b2d7de commit 3b15418

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

rust/0658-find-k-closest-elements.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
impl Solution {
2+
pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
3+
let (mut l, mut r) = (0, arr.len() - 1);
4+
5+
while r - l >= k as usize {
6+
if x - arr[l] <= arr[r] - x {
7+
r -= 1;
8+
} else {
9+
l += 1;
10+
}
11+
}
12+
13+
arr[l..r + 1].to_vec()
14+
}
15+
}

0 commit comments

Comments
 (0)