/**
*
* @author gentleKay
* 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], return6.
*
* 给定n个非负整数,代表一个高程图,其中每根杆的宽度为1,计算下雨后它能捕获多少水。
* 例如,
* 给定[0,1,0,2,1,0,1,3,2,1,2,1],返回6。
*/
题目的图片如图所示:
分析:我们先遍历找到数组中最大的值并标记。
找到之后分别求左边和右边的积水值并相加。先进行遍历左边的部分,求积水的和。
右边的部分和左边一样。遍历的方向需要注意一下。
如果这样还是有点不理解的话,直接看代码并配合着图一起有助于你的理解。
代码:
/** * * @author gentleKay * 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], return6. * * 给定n个非负整数,代表一个高程图,其中每根杆的宽度为1,计算下雨后它能捕获多少水。 * 例如, * 给定[0,1,0,2,1,0,1,3,2,1,2,1],返回6。 */ public class Main33 { public static void main(String[] args) { // TODO Auto-generated method stub int[] A = {0,1,0,2,1,0,1,3,2,1,2,1}; System.out.println(Main33.trap(A)); } public static int trap(int[] A) { int maxMid = 0; int left = 0;int right = 0; int sum = 0; for (int i=0;i<A.length;i++) { // 找到数组中最高的 if (A[i] > A[maxMid]) { maxMid = i; } } for (int i=0;i<maxMid;i++) { //遍历左边 if (A[i] > left) { left = A[i]; }else { sum = sum + left - A[i]; } } for (int i=A.length-1;i>maxMid;i--) { // 遍历右边 if (A[i] > right) { right = A[i]; }else { sum = sum + right - A[i]; } } return sum; } }