Skip to content

Commit 1df697e

Browse files
committed
[feat ]: leetcode 42 with rust
1 parent a54e097 commit 1df697e

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
File renamed without changes.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
impl Solution {
2+
pub fn trap(height: Vec<i32>) -> i32 {
3+
// suppose that the left of an unknow sequence is the level of the water.
4+
let mut boundary_idx = 0;
5+
let mut curr_water_level = *height.first().unwrap();
6+
let mut ret = 0;
7+
let mut acc_water = 0;
8+
9+
for (i, &h) in height.iter().enumerate() {
10+
if curr_water_level <= h {
11+
// we have completed a trap of water.
12+
println!("Accumulate {}, from {} to {}", acc_water, boundary_idx, i);
13+
boundary_idx = i;
14+
curr_water_level = h;
15+
ret += acc_water;
16+
acc_water = 0;
17+
} else {
18+
// continuously accumulate water
19+
acc_water += curr_water_level - h;
20+
}
21+
}
22+
23+
// But in some case, the above assumption doesn't hold, we should use the other endpoint as the level of the water.
24+
// when `acc_water != 0`, it means that this trap of water didn't have a correct endpoint.
25+
if acc_water != 0 {
26+
acc_water = 0;
27+
curr_water_level = *height.last().unwrap();
28+
let old_boundary_idx = boundary_idx;
29+
boundary_idx = height.len() - 1;
30+
for (i, &h) in height.iter().enumerate().rev() {
31+
if i < old_boundary_idx {
32+
break;
33+
}
34+
if curr_water_level <= h {
35+
println!("*Accumulate {}, from {} back {}", acc_water, i, boundary_idx);
36+
curr_water_level = h;
37+
ret += acc_water;
38+
acc_water = 0;
39+
boundary_idx = i;
40+
} else {
41+
acc_water += curr_water_level - h;
42+
}
43+
}
44+
}
45+
ret
46+
}
47+
}

0 commit comments

Comments
 (0)