題目描述(難度中)
給定 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
鏈接
https://leetcode-cn.com/problems/container-with-most-water/
思路
1、暴力枚舉,將每一種組合對應的面積計算出來,然後選出最大的面積,顯然是不合適的,時間複雜度爲O(n2)
2、雙指針,使用兩個指針分別指向頭尾。由於矩形的高是由較短的邊決定的,那麼每次我們將指向較短的邊的指針向指向較長的邊的指針的方向移動,尋找比當前邊更高的邊,如果新找到的邊較之前短,因爲寬度是在縮減的,所以面積一定會更小,所以只能找更長的邊。同理,如果移動較長的邊的指針,由於高度不可能更高,而寬度在減小,面積一定會更小。
注意:
在內層循環移動指針時,要注意到指針的移動範圍問題,不能越界。
代碼
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0;
int j = height.size() - 1;
int maxarea = 0;
while(i < j){
bool flag = height[i] < height[j] ? true : false;
int temparea = (j-i) * (flag ? height[i] : height[j]);
if(maxarea < temparea){
maxarea = temparea;
}
if(flag){
int h = height[i];
while(i < j && height[i] <= h){
i++;
}
}
else{
int h = height[j];
while(j > i && height[j] <= h){
j--;
}
}
}
return maxarea;
}
};