Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed May 1, 2024
1 parent 00fbe40 commit 269e821
Showing 1 changed file with 19 additions and 25 deletions.
44 changes: 19 additions & 25 deletions src/problem_0042_trapping_rain_water/two_pointers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,32 @@ pub struct Solution;

impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let mut iter = height.iter().map(|&x| x as u32);
let mut result = 0;
let mut iter = height.into_iter();

if let (Some(mut left), Some(mut right)) = (iter.next(), iter.next_back()) {
'outer: loop {
if left < right {
for middle in &mut iter {
if middle < left {
result += left - middle;
} else {
left = middle;

continue 'outer;
}
let mut left_max = 0;
let mut right_max = 0;

'outer: while let Some(left) = iter.next() {
if left < left_max {
result += left_max - left;
} else {
left_max = left;
}

while right_max < left_max {
if let Some(right) = iter.next_back() {
if right < right_max {
result += right_max - right;
} else {
right_max = right;
}
} else {
while let Some(middle) = iter.next_back() {
if middle < right {
result += right - middle;
} else {
right = middle;

continue 'outer;
}
}
break 'outer;
}

break;
}
}

result
result as _
}
}

Expand Down

0 comments on commit 269e821

Please sign in to comment.