1、題目介紹
給你 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
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/container-with-most-water
2、解題思路
2.1、暴力方法
class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int len = height.length;
for(int i = 0 ; i < len; i++){
for(int j = i + 1; j < len; j ++){
maxArea = Math.max(maxArea,Math.min(height[i],height[j]) * (j - i));
}
}
return maxArea;
}
}
2.2、雙指針
class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int len = height.length;
int left = 0,right = len - 1;
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;
}
}