標籤:div href desc ret return log == odi mil
題目連結: https://leetcode.com/problems/trapping-rain-water/?tab=Description
Problem: 根據所給數組的值,按照的。求解積水最大體積。 首先對所給數組進行遍曆操作,求出最大高度所對應的下標為maxIndex 之後從左向右進行遍曆,設定左邊高度為leftMax 並初始化為 height[0],從i==1到i==maxIndex進行遍曆。不斷更新water,以及leftMax 當height[I]小於leftMax時,water += leftMax - height 當height[i]大於leftMax時,leftMax = height[I] 之後從i==height.length - 2到下標 I == maxIndex進行遍曆操作 初始化rightMax = height[height.length-1] 當height[I]小於rightMax時,water+=rightMax - height[I] 當height[I]大於rightMax時,rightMax = height[I]
函數結果返回water 參考代碼:
package leetcode_50;/*** * * @author pengfei_zheng * 求積水的體積 */public class Solution42 { public static int trap(int[] height) { if (height.length <= 2) return 0; int max = -1; int maxIndex = 0; for (int i = 0; i < height.length; i++) { if (height[i] > max) { max = height[i]; maxIndex = i; } } int leftMax = height[0]; int water = 0; for (int i = 1; i < maxIndex; i++) { if (height[i] > leftMax) { leftMax = height[i]; } else { water += leftMax - height[i]; } } int rightMax = height[height.length - 1]; for (int i= height.length - 2; i > maxIndex; i--) { if (height[i] > rightMax) { rightMax = height[i]; } else { water += rightMax - height[i]; } } return water; } public static void main(String[]args){// int []height={0,1,0,2,1,0,1,3,2,1,2,1}; int []height={10,0,11,0,10}; System.out.println(trap(height)); }}
LeetCode 42 Trapping Rain Water(積水體積)