【leetcode】【hot100】11盛最多水的容器

題目描述:

https://leetcode-cn.com/problems/container-with-most-water/

給你 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

說明:你不能傾斜容器,且 n 的值至少爲 2。

思路:

代碼實現:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0, r = height.size()-1;
        int area = 0;
        while(l<r){
            int res = min(height[l], height[r]) * (r - l);
            area = max(area,res);
            height[l] < height[r] ? ++l : --r;
        }
        return area;
    }
};
優化:遇到重複的高度,跳過
class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0, r = height.size()-1;
        int area = 0;
        while(l<r){
            int h = min(height[l], height[r]);
            int res = h * (r - l);
            area = max(area,res);
            while(l<r && h == height[l]) ++l;
            while(l<r && h == height[r]) --r;
        }
        return area;
    }
};

參考:https://www.cnblogs.com/grandyang/p/4455109.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章