Container With Most Water. 盛最多水的容器.
一、題目
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input:[1,8,6,2,5,4,8,3,7]
Output: 49
題目翻譯:
給定 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。
二、解題方案
思路:
雙指針法:
由線段長度構成的數組中使用兩個指針,一個放在開始,一個置於末尾。 此外,我們會使用變量 maxareamaxarea 來持續存儲到目前爲止所獲得的最大面積。 在每一步中,我們會找出指針所指向的兩條線段形成的區域,更新 maxareamaxarea,並將指向較短線段的指針向較長線段那端移動一步。
代碼實現:
public class Solution {
public int maxArea(int[] height) {
int maxarea = 0, l = 0, r = height.length - 1;
while (l < r) {
maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r])
l++;
else
r--;
}
return maxarea;
}
}