-
Notifications
You must be signed in to change notification settings - Fork 0
/
42.接雨水.rs
35 lines (34 loc) · 957 Bytes
/
42.接雨水.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
* @lc app=leetcode.cn id=42 lang=rust
*
* [42] 接雨水
*/
// @lc code=start
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
if height.len() == 0 {
return 0;
}
let (mut left, mut right): (usize, usize) = (0, height.len() - 1);
let (mut ans, mut left_max, mut right_max): (i32, i32, i32) = (0, 0, 0);
while left < right {
if height[left] < height[right] {
if height[left] >= left_max {
left_max = height[left];
} else {
ans += (left_max - height[left]);
}
left += 1;
} else {
if height[right] >= right_max {
right_max = height[right];
} else {
ans += (right_max - height[right]);
}
right -= 1;
}
}
ans
}
}
// @lc code=end