Skip to content

Commit e92d85c

Browse files
committed
feat: add rust solution to lcof problem: No.53 - |
面试题 53 - I. 在排序数组中查找数字 I
1 parent bfcd18b commit e92d85c

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

lcof/面试题53 - I. 在排序数组中查找数字 I/README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,48 @@ var search = function (nums, target) {
200200
};
201201
```
202202

203+
### **Rust**
204+
205+
```rust
206+
impl Solution {
207+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
208+
fn my_search(nums: &Vec<i32>, target: i32, left: i32, right: i32) -> i32 {
209+
if left > right {
210+
return 0;
211+
}
212+
213+
let index = (right - left) / 2 + left;
214+
let num = nums[index as usize];
215+
if num > target {
216+
my_search(nums, target, left, index - 1)
217+
} else if num < target {
218+
my_search(nums, target, index + 1, right)
219+
} else {
220+
// 搜索边界
221+
let mut count = 1;
222+
for i in (0..index).rev() {
223+
if nums[i as usize] == target {
224+
count += 1;
225+
} else {
226+
break;
227+
}
228+
}
229+
for i in (index + 1)..nums.len() as i32 {
230+
if nums[i as usize] == target {
231+
count += 1;
232+
} else {
233+
break;
234+
}
235+
}
236+
count
237+
}
238+
}
239+
240+
my_search(&nums, target, 0, nums.len() as i32 - 1)
241+
}
242+
}
243+
```
244+
203245
### **...**
204246

205247
```
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
impl Solution {
2+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
3+
fn my_search(nums: &Vec<i32>, target: i32, left: i32, right: i32) -> i32 {
4+
if left > right {
5+
return 0;
6+
}
7+
8+
let index = (right - left) / 2 + left;
9+
let num = nums[index as usize];
10+
if num > target {
11+
my_search(nums, target, left, index - 1)
12+
} else if num < target {
13+
my_search(nums, target, index + 1, right)
14+
} else {
15+
// 搜索边界
16+
let mut count = 1;
17+
for i in (0..index).rev() {
18+
if nums[i as usize] == target {
19+
count += 1;
20+
} else {
21+
break;
22+
}
23+
}
24+
for i in (index + 1)..nums.len() as i32 {
25+
if nums[i as usize] == target {
26+
count += 1;
27+
} else {
28+
break;
29+
}
30+
}
31+
count
32+
}
33+
}
34+
35+
my_search(&nums, target, 0, nums.len() as i32 - 1)
36+
}
37+
}

0 commit comments

Comments
 (0)