給你 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
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/container-with-most-water
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
//方法一:暴力法
//1.left bar x, right bar y, (x-y)*height_diff O(n^2)
//2.求最大值
public int maxArea(int[] height) {
if (height == null || height.length <= 0) {
return 0;
}
int maxArea = 0;
for (int i = 0; i < height.length - 1; i++) {
for (int j = i + 1; j < height.length; j++) {
int area = (j - i) * Math.min(height[i], height[j]);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
//方法二:
//1.首先考慮最外圍兩條線段圍城的區域,爲了使面積最大化,需要考慮更長的兩條線段之間的區域
//2.加入移動較長線段的指針向內側移動,面積將受限於較短的線段而不會獲得任何增加
//3.移動較短線段的指針,雖然寬度在減少,但是指針會得到一條較長的線段,從而有助於面積的增大
public int maxArea(int[] height) {
int maxArea = 0;
int left = 0, right = height.length - 1;
while (left < right) {
maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right]));
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxArea;
}
//方法三:
//1.定義兩個指針,從數組兩邊開始遍歷組成的矩形,並記錄面積
//2.左右線段,哪邊較低,哪邊往中間移動
//3.當兩個指針匯合時則遍歷完成,返回最大面積
public int maxArea(int[] height) {
int maxArea = 0;
int left = 0, right = height.length - 1;
while (left < right) {
int width = right - left;
int minHeight = height[right] < height[left] ? height[right--] : height[left++];
maxArea = Math.max(maxArea,width * minHeight);
}
return maxArea;
}
//基於方法二進行優化
public int maxArea(int[] height) {
int maxArea = 0, minHeight = 0;
int left = 0, right = height.length - 1;
while (left < right) {
if (height[left] <= height[right]) {
minHeight = height[left];
maxArea = Math.max(maxArea, (right - left) * minHeight);
while (left < right && height[left] <= minHeight) left++;
} else {
minHeight = height[right];
maxArea = Math.max(maxArea, (right - left) * minHeight);
while (left < right && height[right] <= minHeight) right--;
}
}
return maxArea;
}