Skip to content

Commit

Permalink
Update 0042.接雨水.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Ainevsia authored and jinbudaily committed Jul 26, 2023
1 parent b3d1a88 commit f3f549d
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions problems/0042.接雨水.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"/>
Expand Down

0 comments on commit f3f549d

Please sign in to comment.