給定 n
個(gè)非負(fù)整數(shù)a1,a2,...,an
,每個(gè)數(shù)代表坐標(biāo)中的一個(gè)點(diǎn) (i, ai)
。在坐標(biāo)內(nèi)畫 n
條垂直線,垂直線 i 的兩個(gè)端點(diǎn)分別為 (i, ai)
和 (i, 0)
。找出其中的兩條線,使得它們與 x
軸共同構(gòu)成的容器可以容納最多的水。
說(shuō)明:你不能傾斜容器,且 n
的值至少為 2。
圖中垂直線代表輸入數(shù)組 [1,8,6,2,5,4,8,3,7]
。在此情況下,容器能夠容納水(表示為藍(lán)色部分)的最大值為 49
。
示例:
輸入: [1,8,6,2,5,4,8,3,7]
輸出: 49
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/container-with-most-water
class Solution {
public int maxArea(int[] height) {
int start = 0 , end = height.length-1;
int ans = 0;
while(start < end){
ans = max(ans,min(height[start],height[end]) *(end-start));
if(height[start] < height[end])
start++;
else
end--;
}
return ans;
}
private int max(int a,int b){ return a>b?a:b; }
private int min(int a,int b){ return a>b?b:a; }
}
【思路】
雙指針,一個(gè)是向前遍歷,一個(gè)向后遍歷
每一次計(jì)算當(dāng)前的兩個(gè)指針圍成的面積
把指向較短線段的指針向較長(zhǎng)線段的那端移動(dòng)