算法第十四周解题报告

问题描述:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

解题思路:

设f(p1, p2)为p1、p2点构成的水槽的盛水面积

则我们要求的目标为max(f(0, height.size()-1));

这个问题可以分解为max(f(0, height.size()-1), max(f(p1, p2))), 其中p1、p2 属于集合{p|0 <= p <= height.size() - 1};

另外我们可以知道,若f(p1, p2)不在端点取最大值,则必有min(h[p1], h[p2]) > min(h[0], h[height -1]), 由此我们可以断言,最大值要不然在端点处取得,要不然就在端点构成的区间内某一大于端点最小值的端点上取得,缩小范围后,继续重复上述推理,可得结果,复杂度为O(n)


代码如下:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0  , right = height.size() -1 , max=0;
        int curA; 
        while(left<right) {  
            curA = (right - left) * (height[left] > height[right] ? height[right] : height[left]);  
            if (height[left]<height[right]) {  
                ++left;  
            } else {  
                --right;  
            }
            max = curA > max ? curA : max;
        }  
        return max;  
    }
};
结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值