Leetcode:Container With Most Water

本文介绍了一种利用双指针优化算法解决“容器最大容量”问题的方法,通过敏感地分析数值特性,实现O(n)的时间复杂度。详细阐述了如何在遍历过程中剔除不可能成为最优解的条件,简化计算过程。

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.

Note: You may not slant the container.

分析:这道题与Trapping Rain Water、Largest Rectangle in Histogram有共通之处。解决这三道题,我们都要保持对数字的敏感性,发现隐含在数字后的性质。对于这道题,container装水的量是有短板决定的。可能大家都知道这点,但如何利用这点来完成一个O(n)的算法则值得思考。Brute-force的算法复杂度为O(n^2),但其实在brute-force算法中的很多计算是不必要的,我们大可在计算的过程中将这些不必要(不可能是最优解)的情况prune掉。对于一个高度的line,我们只需求以该line为短板的最大装水量即可,满足最大装水量的container是由该line和离该line最远的且比该line高的line组成。在代码中我们可以用two pointers来实现上述思想。一旦一个line是以短板的角色出现后,我们便可以将其剔除,在后续计算中不考虑以它为边界的container。代码如下:

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

 

转载于:https://www.cnblogs.com/Kai-Xing/p/4226696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值