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.
第一印象就是暴力求解法,用两个循环O(N^2)时间复杂度,我以为这道题很简单,结果还是我太年轻,当我看到一个连续15000个数的案例时,直接给跪,不用说超时了。

int maxArea(int* height, int heightSize) 
{
    int max=0,i,j,minheight,temp;
    for(i=0;i<heightSize;i++)
        for(j=i+1;j<heightSize;j++)
        {
            minheight=height[i]<height[j]?height[i]:height[j];
            temp=minheight*(j-i);
            max=temp>max?temp:max;
        }
    return max;
}

后来我去看别人写的,发现了一种贪心算法,时间复杂度为O(N)。它的思想类似贪心算法,用两个下标i,j分别指向两端,比较它们的高度假设height[i]小于height[j],矩形的面积(j-i)*height[i]如果大于之前的最大面积就更新,接下来一步就是移动i或者j。移动哪个呢,假设向左移动j,矩形的底边减少了,不论此时的height[j]是比之前增大还是减少,矩形的面积都是减少,所以应该向右移动i。所以原则就是那边高度低就移那边。很巧妙,但是我想不到啊,还是要勤加练习。这样运行时间8ms,击败70%的人。

int maxArea(int* height, int heightSize) 
{
    int max=0,i,j,minheight,temp;
    for(i=0,j=heightSize-1;i<j;)
    {
        minheight=height[i]<height[j]?height[i]:height[j];
        temp=(j-i)*minheight;
        max=temp>max?temp:max;
        if(height[i]<height[j])
            i++;
        else
            j--;
    }
    return max;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值