|
| 1 | +/** |
| 2 | + * [42] 接雨水 |
| 3 | + * |
| 4 | + * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 |
| 5 | + * |
| 6 | + * 示例 1: |
| 7 | + * <img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rainwatertrap.png" style="height: 161px; width: 412px;" /> |
| 8 | + * |
| 9 | + * 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1] |
| 10 | + * 输出:6 |
| 11 | + * 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 |
| 12 | + * |
| 13 | + * 示例 2: |
| 14 | + * |
| 15 | + * 输入:height = [4,2,0,3,2,5] |
| 16 | + * 输出:9 |
| 17 | + * |
| 18 | + * |
| 19 | + * 提示: |
| 20 | + * |
| 21 | + * n == height.length |
| 22 | + * 1 <= n <= 2 * 10^4 |
| 23 | + * 0 <= height[i] <= 10^5 |
| 24 | + * |
| 25 | + */ |
| 26 | +pub struct Solution {} |
| 27 | + |
| 28 | +// problem: https://leetcode.cn/problems/trapping-rain-water/ |
| 29 | +// discuss: https://leetcode.cn/problems/trapping-rain-water/discuss/?currentPage=1&orderBy=most_votes&query= |
| 30 | + |
| 31 | +// submission codes start here |
| 32 | + |
| 33 | +impl Solution { |
| 34 | + pub fn trap(height: Vec<i32>) -> i32 { |
| 35 | + let mut stack: Vec<(usize, i32)> = vec![]; |
| 36 | + let mut res = 0; |
| 37 | + let mut bsum = 0; |
| 38 | + for (i, v) in height.iter().enumerate() { |
| 39 | + if stack.len() > 0 { |
| 40 | + if *v >= stack[0].1 { |
| 41 | + let (j, h) = stack[0]; |
| 42 | + res += (i - j) as i32 * h - bsum; |
| 43 | + stack.clear(); |
| 44 | + bsum = 0; |
| 45 | + } else { |
| 46 | + while stack[stack.len()-1].1 < *v { |
| 47 | + stack.pop(); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + bsum += v; |
| 52 | + stack.push((i, *v)); |
| 53 | + } |
| 54 | + if stack.len() > 1 { |
| 55 | + let mut sidx = stack[0].0; |
| 56 | + for (eidx, h) in &stack[1..] { |
| 57 | + bsum = 0; |
| 58 | + for i in (sidx+1)..=*eidx { |
| 59 | + bsum += height[i]; |
| 60 | + } |
| 61 | + res += (eidx - sidx) as i32 * h - bsum; |
| 62 | + sidx = *eidx; |
| 63 | + } |
| 64 | + } |
| 65 | + res |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// submission codes end |
| 70 | + |
| 71 | +#[cfg(test)] |
| 72 | +mod tests { |
| 73 | + use super::*; |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_42() { |
| 77 | + assert_eq!(Solution::trap(vec![0,1,0,2,1,0,1,3,2,1,2,1]), 6); |
| 78 | + assert_eq!(Solution::trap(vec![4,2,0,3,2,5]),9); |
| 79 | + } |
| 80 | +} |
0 commit comments