From 6e7e5e0fae032918f5288e86c177c3e40916c6e0 Mon Sep 17 00:00:00 2001 From: Zhipeng Xu Date: Sat, 8 Jul 2023 22:13:12 +0800 Subject: [PATCH] =?UTF-8?q?Update=200042.=E6=8E=A5=E9=9B=A8=E6=B0=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0042.接雨水.md | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index db66095d..833a7613 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -926,6 +926,56 @@ int trap(int* height, int heightSize) { * 空间复杂度 O(1) +Rust + +双指针 + +```rust +impl Solution { + pub fn trap(height: Vec) -> 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 { + 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 + } +} +``` +