Leetcode11.Container With Most Water盛最多水的容器
阿新 • • 發佈:2018-12-22
給定 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
方法一:暴力法
class Solution { public: int maxArea(vector<int>& height) { int len = height.size(); int MAX = 0; for(int i = 0; i < len; i++) { for(int j = i + 1; j < len; j++) { MAX = max(MAX, (j - i) * min(height[i], height[j])); } } return MAX; } };
方法二雙指標:
雙指標:為了使面積最大化,我們需要考慮更長的兩條線段之間的區域。如果我們試圖將指向較長線段的指標向內側移動,矩形區域的面積將受限於較短的線段而不會獲得任何增加。但是,在同樣的條件下,移動指向較短線段的指標儘管造成了矩形寬度的減小,但卻可能會有助於面積的增大。
class Solution { public: int maxArea(vector<int>& height) { int MAX = 0; int low = 0; int high = height.size() - 1; while(low < high) { MAX = max(MAX, (high - low) * min(height[low], height[high])); if(height[low] < height[high]) { low++; } else { high--; } } return MAX; } };