Trapping Rain Water
Trapping Rain Water
Problem Description
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Approach: Two Pointers
Intuition
The key insight is that at any position, the water level is dtermined the minimum of the maximum heights to its left and right. We can use two pointers moving towards each other from both ends.
Algorithm
- Initialize two pointer
left
andright
at the beginning and each of the array. - Keep track of
leftMax
andrightMax
, the maximum heights seen so far from left and right respectively. - Move the pointer with smaller height:
- If height[left] < height[right], process the left side
- The water level at position
left
is determined byleftMax
(since we knowrightMax
is at leastheight[right]
which is greater) - If current height is less than
leftMax
, we can trapleftMax - heights[left]
water - Move
left
pointer forward
- Apply the same logic for the right side
- Continue until pointers meet
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
29class Solution {
public:
int trap(vector<int>& height){
int len = height.size();
int left = 0;
int right = len - 1;
int leftMax = 0;
int rightMax = 0;
int water = 0;
while(left < right){
if(height[left] < height[right]){
if(height[left] >= leftMax){
leftMax = height[left];
}else{
water += leftMax - height[left];
}
left++;
}else{
if(height[right] >= rightMax){
rightMax = height[right];
}else{
water += rightMax - height[right];
}
right--;
}
}
return water;
}
};
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 YouChen's Blog!