Trapping Rain Water
问题:
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.
思路:
数组的特别,拿到最高点的值,左右两边再分别测试
我的代码:
public class Solution { public int trap(int[] A) { if(A == null || A.length == 0) return 0; int maxIndex = -1; int maxValue = Integer.MIN_VALUE; for(int i = 0; i < A.length; i++) { if(maxValue < A[i]) { maxIndex = i; maxValue = A[i]; } } int maxRes = 0; int curMax = A[0]; for(int i = 1; i <= maxIndex; i++) { if(A[i] < curMax) { maxRes += curMax - A[i]; } else { curMax = A[i]; } } curMax = A[A.length - 1]; for(int i = A.length - 1; i >= maxIndex; i--) { if(A[i] < curMax) { maxRes += curMax - A[i]; } else { curMax = A[i]; } } return maxRes; } }
学习之处:
抓住数组最高点的特征