LeetCode | 11. Container With Most Water

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

解题思路:注意测试样例会出现高度为0的情况.
解法一:暴力枚举,O(n^2),47/49Passed,果断超时

class Solution {
public:
        int min(int a,int b)
        {
            return a<b?a:b;
        }

        int maxArea(vector<int>& height)
        {
            int len = height.size(), mmax = 0, t_sum = 0;
            for(int i=0;i<len;i++)
            {
                for(int j=i+1;j<len;j++)
                {
                    int tmin = min(height[i],height[j]), tmax = max(height[i],height[j]);
                    if(tmin == 0)
                    {
                        continue;
                    }
                    t_sum = 0;
                    t_sum += (j-i)*tmin;
                    if(t_sum > mmax)
                    {
                        mmax = t_sum;
                    }
                }
            }
            return mmax;
        }
};

解法二:从两端向中间枚举,每次比较面积与最优解的大小,更新最优解.
若height[L]< height[R],L++;否则R–;
证明过程:
假设这个算法找到的解不是最优解.那么存在hl,hr,使得这两个高度组成的矩形面积最大.那么我们算法在执行过程中肯定先遇到了其中的某个,但没有同时遇到.假设算法执行时遇到了hl(并且假设hl高度更大,不然可以换成hr).他肯定还没有遇到hr,不然最优解已经出现并更新.那么此时若hl继续移动,肯定不会同时遇到了,假设此时hl不移动.但是由题意可知,hl不移动的情况只有两种:
1.另一个指针也指向hl,两指针相遇,算法结束.
2.另一指针指向了ht,并且ht的值不必hl小.此时hl要移动.
那么矛盾出现了,既然hl是hl hr中较大者,现在遇到了ht,并且组成的矩形的长和宽都不比hl,hr组成的小,面积不小于它,那么与hl,hr为最优解矛盾.
所以算法的正确性得以证明.

//19ms AC
class Solution {
public:
    int min(int a,int b)
    {
        return a<b?a:b;
    }

    int maxArea(vector<int>& height)
    {
        int len = height.size(), mmax = 0, t_sum = 0;
        int left = 0, right = len-1;
        while(left < right)
        {
            int tmin = min(height[left],height[right]);
            t_sum = (right-left)*tmin;
            if(t_sum > mmax)
            {
                mmax = t_sum;
            }
            if(height[left] < height[right])
            {
                left++;
            }
            else
            {
                right--;
            }
        }
        return mmax;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值