LeetCode:盛最多水的容器【11】
阿新 • • 發佈:2018-09-23
出發 UNC jpg 分析 左右 quest highlight 圖片 leetcode
LeetCode:盛最多水的容器【11】
題目描述
給定 n 個非負整數 a1,a2,...,an,每個數代表坐標中的一個點 (i, ai) 。在坐標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少為 2。
圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為 49。
示例:
輸入: [1,8,6,2,5,4,8,3,7] 輸出: 49
題目分析
首先說明木桶的水量是由最短的木板決定的,既然這樣,依然套用雙指針檢測模型即可!
左右兩個指針分別從兩頭出發,ans嘗試記錄每中情況盛水量的最大值,盛水量的計算方法是:最短的木板高度【Math.min(height[left],height[right])】,以及木板長度【right-left】的乘積。
最後輸出ans即可。
Java題解
class Solution { public int maxArea(int[] height) { int left = 0 ; int right = height.length-1; int ans = 0; while (left<right) { int tmp = Math.min(height[left],height[right]); ans =Math.max(ans,(right-left)*tmp); if(height[left]<=height[right]) left++; else right--; } return ans; } }
LeetCode:盛最多水的容器【11】