题目描述:(链接)
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
题目解析:
遍历数组,找到当前元素左边的最大值max_left和右边的最大值max_right,如果min(max_left, max_right) < 当前元素高度h,将h - min(max_left, max_right)加到结果上去。
1 class Solution { 2 public: 3 int trap(vector<int>& height) { 4 int length = height.size(); 5 vector<int> max_left(length, 0); 6 vector<int> max_right(length, 0); 7 8 int result = 0; 9 10 for (int i = 1; i < length; ++i) { 11 max_left[i] = max(max_left[i - 1], height[i - 1]); 12 max_right[length - 1 - i] = max(max_right[length - i], height[length - i]); 13 } 14 15 for (int i = 0; i < length; ++i) { 16 int h = min(max_left[i], max_right[i]); 17 if (h > height[i]) { 18 result += (h - height[i]); 19 } 20 } 21 22 return result; 23 } 24 };