mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 0042.接雨水.md
This commit is contained in:
@ -926,6 +926,56 @@ int trap(int* height, int heightSize) {
|
||||
* 空间复杂度 O(1)
|
||||
|
||||
|
||||
Rust
|
||||
|
||||
双指针
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn trap(height: Vec<i32>) -> i32 {
|
||||
let n = height.len();
|
||||
let mut max_left = vec![0; height.len()];
|
||||
let mut max_right = vec![0; height.len()];
|
||||
max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| {
|
||||
let lmax = lm.max(height[idx]);
|
||||
let rmax = rm.max(height[n - 1 - idx]);
|
||||
*x = lmax; *y = rmax;
|
||||
(lmax, rmax)
|
||||
});
|
||||
height.iter().enumerate().fold(0, |acc, (idx, x)| {
|
||||
let h = max_left[idx].min(max_right[idx]);
|
||||
if h > 0 { h - x + acc } else { acc }
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
单调栈
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn trap(height: Vec<i32>) -> i32 {
|
||||
let mut stack = vec![];
|
||||
let mut ans = 0;
|
||||
for (right_pos, &right_h) in height.iter().enumerate() {
|
||||
while !stack.is_empty() && height[*stack.last().unwrap()] <= right_h {
|
||||
let mid_pos = stack.pop().unwrap();
|
||||
if !stack.is_empty() {
|
||||
let left_pos = *stack.last().unwrap();
|
||||
let left_h = height[left_pos];
|
||||
let top = std::cmp::min(left_h, right_h);
|
||||
if top > height[mid_pos] {
|
||||
ans += (top - height[mid_pos]) * (right_pos - left_pos - 1) as i32;
|
||||
}
|
||||
}
|
||||
}
|
||||
stack.push(right_pos);
|
||||
}
|
||||
ans
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user