Skip to content

Commit 359f327

Browse files
committed
feat: add rust solution to lc problem: No.0658
No.0658.Find K Closest Elements
1 parent 81da1d5 commit 359f327

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

solution/0600-0699/0658.Find K Closest Elements/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,28 @@ class Solution {
102102
}
103103
```
104104

105+
### **Rust**
106+
107+
双指针:
108+
109+
```rust
110+
impl Solution {
111+
pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
112+
let n = arr.len();
113+
let mut l = 0;
114+
let mut r = n;
115+
while r - l != k as usize {
116+
if (arr[l] - x).abs() <= (arr[r - 1] - x).abs() {
117+
r -= 1;
118+
} else {
119+
l += 1;
120+
}
121+
}
122+
arr[l..r].to_vec()
123+
}
124+
}
125+
```
126+
105127
### **...**
106128

107129
```

solution/0600-0699/0658.Find K Closest Elements/README_EN.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,26 @@ class Solution {
8686
}
8787
```
8888

89+
### **Rust**
90+
91+
```rust
92+
impl Solution {
93+
pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
94+
let n = arr.len();
95+
let mut l = 0;
96+
let mut r = n;
97+
while r - l != k as usize {
98+
if (arr[l] - x).abs() <= (arr[r - 1] - x).abs() {
99+
r -= 1;
100+
} else {
101+
l += 1;
102+
}
103+
}
104+
arr[l..r].to_vec()
105+
}
106+
}
107+
```
108+
89109
### **...**
90110

91111
```
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 n = arr.len();
4+
let mut l = 0;
5+
let mut r = n;
6+
while r - l != k as usize {
7+
if (arr[l] - x).abs() <= (arr[r - 1] - x).abs() {
8+
r -= 1;
9+
} else {
10+
l += 1;
11+
}
12+
}
13+
arr[l..r].to_vec()
14+
}
15+
}

0 commit comments

Comments
 (0)