题目:
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.java
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.code
解答:it
public class Solution { public int trap(int[] height) { //左边比右边小或者大均可以盛水,因此咱们不能直接肯定右边是否会有一个柱子比较大,能盛全部如今积攒的水。 //那么咱们就找到中间最大的那个柱子,把它分红左右两边,那么无论从左边仍是右边都能保证最后能够有最高的柱子在,以前盛的水都是有效的 if (height.length <= 2) return 0; int maxHeight = 0, maxIndex = 0; int result = 0; //find the max height and its index for (int i = 0; i < height.length; i++) { if (height[i] > maxHeight) { maxHeight = height[i]; maxIndex = i; } } //left part int maxLeft = height[0]; for (int i = 1; i < maxIndex; i++) { if (height[i] > maxLeft) { maxLeft = height[i]; } else { result += maxLeft - height[i]; } } //right part int maxRight = height[height.length - 1]; for (int i = height.length - 2; i > maxIndex; i--) { if (height[i] > maxRight) { maxRight = height[i]; } else { result += maxRight - height[i]; } } return result; } }