Description:
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
.
Solution:
先把任何比左右都大的转折点找到(以及第一个开始下降的点和最后一个下降的点)
然后对这些所有的转折点进行”归并“,”归并“的方式是如果某个转折点比左右的转折点都小于等于,就归并。
最后归并后的转折点即为所求。
后来看了其他人的解法,扫两次即可。
<span style="font-size:18px;">public class Solution {
public int trap(int[] height) {
int n = height.length;
if (n == 0)
return 0;
int start = 0;
for (; start < n; start++)
if (start + 1 < n && height[start] > height[start + 1])
break;
int end = n - 1;
for (; end >= 0; end--)
if (end - 1 >= 0 && height[end] > height[end - 1])
break;
if (start >= end)
return 0;
int[] mark = new int[n];
int tot = 0;
mark[tot++] = start;
for (int i = start + 1; i < end; i++) {
if (height[i] >= height[i - 1] && height[i] >= height[i + 1])
mark[tot++] = i;
}
mark[tot++] = end;
for (int i = tot - 1; i > 0; i--) {
while (i + 1 < tot && height[mark[i]] <= height[mark[i + 1]]
&& height[mark[i]] <= height[mark[i - 1]]) {
for (int j = i; j < tot; j++)
mark[j] = mark[j + 1];
tot--;
}
}
int sum = 0;
int min;
for (int i = 1; i < tot; i++) {
min = Math.min(height[mark[i - 1]], height[mark[i]]);
for (int j = mark[i - 1] + 1; j < mark[i]; j++)
if (min > height[j])
sum += min - height[j];
}
return sum;
}
}</span>