Skip to content

Commit cb642a2

Browse files
committed
1
1 parent 68affdc commit cb642a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

notes/src/day1/lc704.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,32 @@ impl Solution {
8484
}
8585
```
8686

87+
## 重写
88+
89+
- 喜欢用左闭右开的区间
90+
- match arm不需要用`,`结尾也是合法的语法
91+
- `Ordering::Less => { right = mid }` 要注意“右开” 又写错了
92+
93+
```rust
94+
95+
use std::cmp::Ordering;
96+
97+
impl Solution {
98+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
99+
let mut left: usize = 0;
100+
let mut right: usize = nums.len();
101+
while left < right {
102+
let mid: usize = left + (right - left) / 2;
103+
let mid_num: &i32 = &nums[mid];
104+
105+
match target.cmp(mid_num) {
106+
Ordering::Equal => { return mid as i32 }
107+
Ordering::Less => { right = mid }
108+
Ordering::Greater => { left = mid + 1 }
109+
}
110+
}
111+
-1i32
112+
}
113+
}
114+
115+
```

0 commit comments

Comments
 (0)