題目描述: LeetCode地址
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.
給定 n 個非負整數 a1,a2,…,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
注: 不能傾斜容器,且 n 的值至少爲 2。
解題思路:
兩線段之間的區域總是取決於較短那條的長度。
我們在由線段長度構成的數組中使用兩個指針,left
放在開始,right
置於末尾。 用變量 maxArea
來表示獲得的最大面積。
即maxArea = min(height[left],height[right]) * (right - left)
在每一次循環中找出指針所指向的兩條線段形成的區域,更新maxArea
,並將指向較短線段的指針向較長線段那端移動一步。
可以查看官方解答的動圖能有更直觀的感受。
思考: 一開始不太清楚爲什麼要將指向較短線段的指針向較長那端移動,原因是要想得到最大的區域面積,就要假設較大的那端是下次循環中較短的那端,可能可以得到更大的區域面積。
代碼:
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while(left < right){
maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
if(height[left] < height[right]){
left++;
}else{
right--;
}
}
return maxArea;
}
}