6.container-with-most-water(装最多水的容器)

来源:互联网 发布:中文域名icp备案 编辑:程序博客网 时间:2024/05/20 09:06

6.container-with-most-water(装最多水的容器)

链接:http://www.lintcode.com/zh-cn/problem/container-with-most-water/

题目描述:

给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai)。画 n 条垂直线,使得 i垂直线的两个端点分别为(i, ai)(i, 0)。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。

 注意事项

容器不可倾斜。

样例

给出[1,3,2], 最大的储水面积是2.

分析:以序列最外面两条边形成的面基为起始面积,找出两条边中较小的一条,索引加一(i++),找出一条更大的边来代替较小的边,以使得整个容器最大。

形象动图如下:https://leetcode.com/media/original_images/11_Container_Water.gif

         


class Solution {public:    /**     * @param heights: a vector of integers     *@return: an integer     */    int maxArea(vector<int> &heights){        // write your code here        int len=heights.size();        int left=0,right=len-1,maxnum=0;        while(left<right)        {            maxnum=max(maxnum,min(heights[left],heights[right])*(right-left));           if(heights[left]<=heights[right])                ++left;            else                --right;        }        return maxnum;    }};


阅读全文
0 0