Skip to content

Commit bed9e8a

Browse files
committed
fix: show lc problem No.1768 rust solution
No.0704.Binary Search
1 parent 6f9911b commit bed9e8a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

solution/0700-0799/0704.Binary Search/README_EN.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,55 @@ var search = function (nums, target) {
132132
};
133133
```
134134

135+
### **Rust**
136+
137+
Cycle:
138+
139+
```rust
140+
use std::cmp::Ordering;
141+
142+
impl Solution {
143+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
144+
let mut l = 0;
145+
let mut r = nums.len();
146+
while l < r {
147+
let mid = l + r >> 1;
148+
match nums[mid].cmp(&target) {
149+
Ordering::Less => l = mid + 1,
150+
Ordering::Greater => r = mid,
151+
Ordering::Equal => return mid as i32,
152+
}
153+
}
154+
-1
155+
}
156+
}
157+
```
158+
159+
Recursion:
160+
161+
```rust
162+
use std::cmp::Ordering;
163+
164+
impl Solution {
165+
fn binary_search(nums: Vec<i32>, target: i32, l: usize, r: usize) -> i32 {
166+
if l == r {
167+
return if nums[l] == target { l as i32 } else { -1 };
168+
}
169+
let mid = l + r >> 1;
170+
match nums[mid].cmp(&target) {
171+
Ordering::Less => Self::binary_search(nums, target, mid + 1, r),
172+
Ordering::Greater => Self::binary_search(nums, target, l, mid),
173+
Ordering::Equal => mid as i32,
174+
}
175+
}
176+
177+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
178+
let r = nums.len() - 1;
179+
Self::binary_search(nums, target, 0, r)
180+
}
181+
}
182+
```
183+
135184
### **...**
136185

137186
```

0 commit comments

Comments
 (0)