11. 盛最多水的容器

个人理解:为很会想到以下时间复杂度为O(n)的思路呢? 由题意可知此题意在比较(i-j)*Height的大小。

本题使i,j分别从两边向中间靠拢,保持了length的单调递减,在length递减的条件下,要比之前的面积大,只有提升height,于是将原本较小的height舍弃,向中间靠拢,看是否有更大的面积。

于是有疑问:你如何确定答案就在收缩的(i,j)对中呢?

是因为,在舍弃较小的height中,只自动舍弃了许多小于当前最大值的方案,(也就是最佳答案不会被舍弃)故选择路线一定会经过最大值的(i,j)对。

原题:

给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (iai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (iai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

 

示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

解决办法:

class Solution {
    public int maxArea(int[] height) {
        int i=1,j=height.length;
        int temp=0;
        while(i<j){
            if(height[i-1]<=height[j-1]){
                temp=Math.max(temp,(j-i)*Math.min(height[j-1],height[i-1]));
                i++;
            }else{
                temp=Math.max(temp,(j-i)*Math.min(height[j-1],height[i-1]));
                j--;
            }
        }
        return temp;
    }
}

思路见下图:来自https://leetcode.com/problems/container-with-most-water/discuss/6099/Yet-another-way-to-see-what-happens-in-the-O(n)-algorithm

  1 2 3 4 5 6
1 x ------- o
2 x x
3 x x x 
4 x x x x
5 x x x x x
6 x x x x x x

 

Next we move the left line and compute (2,6). Now if the right line is shorter, all cases below (2,6) are eliminated.

 

  1 2 3 4 5 6
1 x ------- o
2 x x       o
3 x x x     |
4 x x x x   |
5 x x x x x |
6 x x x x x x

 

And no matter how this o path goes, we end up only need to find the max value on this path, which contains n-1 cases.

  1 2 3 4 5 6
1 x ------- o
2 x x - o o o
3 x x x o | |
4 x x x x | |
5 x x x x x |
6 x x x x x x

 

Hope this helps. I feel more comfortable seeing things this way.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值