题目描述:
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.
样例
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.
分析:双指针操作,只要注意处理好细节就可以了
public class Solution { /** * @param heights: a list of integers * @return: a integer */ public int trapRainWater(int[] heights) { int i=0; int area=0; while(i<heights.length-1){ if(heights[i]==0){ i++; } else{ int j=i+1; int max=i+1; while(j<heights.length && heights[j]<heights[i]){ if(max<heights.length && heights[j]>heights[max]){ max=j; } j++; } if(j<heights.length){ int sum=0; for(int k=i+1; k<j; k++){ sum+=heights[k]; } area+=(j-i-1)*Math.min(heights[i], heights[j])-sum; i=j; } else{ int sum=0; for(int k=i+1; k<max; k++){ sum+=heights[k]; } area+=(max-i-1)*Math.min(heights[i], heights[max])-sum; i=max; } } } return area; } }