【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

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