높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Input: height = [4,2,0,3,2,5]
Output: 9
class Solution {
public:
int trap(vector<int>& height) {
vector<int>::iterator left = height.begin();
vector<int>::iterator right = height.end() - 1;
int volume = 0;
int leftHeight = *(left);
int rightHeight = *(right);
while (left != right)
{
if (leftHeight <= rightHeight)
{
left++;
if (leftHeight <= *(left)) leftHeight = *(left);
if (leftHeight > *(left)) volume += leftHeight - *(left);
}
else if (leftHeight >= rightHeight)
{
right--;
if (rightHeight <= *(right)) rightHeight = *(right);
if (rightHeight > *(right)) volume += rightHeight - *(right);
}
}
return volume;
}
};
Runtime 11 ms / Memory 19.7 MB
https://leetcode.com/problems/trapping-rain-water/submissions/880025942/