Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c14b21

Browse files
author
guangsheng.li01
committed
Solved 0042
1 parent 875b601 commit 1c14b21

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

‎src/a0042_trapping_rain_water.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* [0042] trapping-rain-water
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
use std::cmp::max;
10+
impl Solution {
11+
pub fn trap(height: Vec<i32>) -> i32 {
12+
if height.len() < 3 {
13+
return 0;
14+
}
15+
16+
let (mut left, mut right, mut depth, mut result) = (0, height.len() - 1, std::i32::MIN, 0);
17+
while left < right {
18+
let p;
19+
if height[left] < height[right] {
20+
p = left;
21+
left += 1;
22+
} else {
23+
p = right;
24+
right -= 1;
25+
}
26+
depth = max(depth, height[p]);
27+
if depth > height[p] {
28+
result += depth - height[p];
29+
}
30+
}
31+
result
32+
}
33+
}
34+
35+
// solution impl ends here
36+
37+
// solution tests starts here
38+
39+
#[cfg(test)]
40+
mod tests {
41+
use super::*;
42+
43+
#[test]
44+
fn test_case0() {
45+
assert_eq!(Solution::trap(vec![0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), 6);
46+
}
47+
}
48+
49+
// solution tests ends here

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod a0009_palindrome_number;
1111
mod a0026_remove_duplicates_from_sorted_array;
1212
mod a0027_remove_element;
1313
mod a0035_search_insert_position;
14+
mod a0042_trapping_rain_water;
1415
mod a0053_maximum_subarray;
1516
mod a0066_plus_one;
1617
mod a0088_merge_sorted_array;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /