个人记录-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.

题目的要求是:
给定一个数组,用数组的下标作为横坐标,数组的内容作为纵坐标,绘制一个个点。
每个点向x轴作垂线;两个垂线构成一个容器。
求出最大的容器(仅算出宽和高的积)。

代码示例:
1、最容易想到的是暴力解法,即不断迭代得到最大值:

public class Solution {
    public int maxArea(int[] height) {
        if(height == null) {
            return 0;
        }

        int max = 0;

        int curr;
        for (int i = 0; i < height.length - 1; ++i) {
            for (int j = i + 1; j < height.length; ++j) {
                curr = (j - i) * (height[i] > height[j] ?
                        height[j] : height[i]);

                if (curr > max) {
                    max = curr;
                }
            }
        }

        return max;
    }
}

这种解法可以得出正确的结果,但是无法满足时间要求。
由于每次移动数组下标时,宽度逐渐增加,而高度的变化是不确定的,因此不得轮询整个数组,算法的复杂度变为O( N2 )。

2、采用双向逼近的方式。
基本思路是:
设置两个下标firstIndex , lastIndex , 一头一尾, 相向而行。
假设firstIndex 指向的挡板较低, lastIndex 指向的挡板较高(height[firstIndex ] < height[lastIndex ]).
下一步移动哪个指针?
– 若移动lastIndex , 无论height[lastIndex -1]是何种高度, 形成的面积都小于之前的面积(宽度和高度都会下降)。
– 若移动firstIndex ,
如果height[firstIndex +1] <= height[firstIndex ],面积一定缩小;
但若height[firstIndex +1] > height[firstIndex ], 面积则有可能增大。
综上,每次都应该移动指向较低挡板的那个下标。

public class Solution {
    public int maxArea(int[] height) {
        if(height == null) {
            return 0;
        }

        int max = 0;
        int firstIndex = 0;
        int lastIndex = height.length - 1;

        int firstHeight, lastHeight, curr;
        while (firstIndex < lastIndex) {
            firstHeight = height[firstIndex];
            lastHeight = height[lastIndex];

            curr = (lastIndex - firstIndex) *
                    (firstHeight > lastHeight ? lastHeight : firstHeight);

            if (curr > max) {
                max = curr;
            }

            if (firstHeight > lastHeight) {
                --lastIndex;
            } else {
                ++firstIndex;
            }
        }

        return max;
    }
}

这种方法降低了不确定性。
由于宽度一开始取的是最大值,因此移动下标后宽度一定是减小的。
在这个条件下,每次的移动就简化为尽可能找到更高的纵坐标。
于是算法复杂度降低为O(N)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值