11. Container With Most Water

来源:互联网 发布:淘宝卷和商品连在一起 编辑:程序博客网 时间:2024/05/22 19:38

标签(空格分隔): leetcode


给定n个非负整数a1,a2,…,an,其中每个表示坐标(i,ai)处的点。绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,找到两条线,它们与x轴一起形成一个容器,使得容器含有最多的水。
注意:您不能倾斜容器,n至少为2。


  1. 给定一个数组,(序列号,数值)形成一个坐标,然后就是选择两个坐标,这两个坐标的 垂线段和x轴形成一个桶,求面积最大的两点围成的桶。

  2. 两个索引可以组成一个底部的宽,高度就是前面所说的线段的长度,而既然是要盛水,高度就是两个线段中较短的一个。

class Solution {public:    int maxArea(vector<int>& height)     {        int mxArea = 0;         int left = 0, right = height.size()-1;        while(left<right)         {            int curArea = min(height[left],height[right])*(right-left);            mxArea = max(curArea,mxArea);            if(height[left]<height[right])                left++;            else if(height[left]>height[right])                right--;            else             {                left++;                right--;            }        }        return mxArea;    }};

【参考文档】
1.LeetCode 11 Container With Most Water(最大水容器)
2.LeetCode】Container With Most Water 解题报告