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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值