Leetcode 11 Container With Most Water

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.

Solution1

  • 这道题实际上是找到两根线,使得两根线之间能聚集的雨水最多,这和42题不一样。这里的思路是从数组两端开始,计算一次两根线之间能聚集多少雨水,完了将较短的那条边移动一格(移动方向是前面的指针往后移,后面的指针往前移),重新计算两根线之间能聚集多少雨水。
public class Solution {
    public int maxArea(int[] height) {
        int result = 0;
        int n = height.length;
        for(int i=0,j=n-1;i<j;){
            result = Math.max(result,Math.min(height[i],height[j])*(j-i));
            if(height[i]<height[j]) i++;
            else j--;
        }
        return result;
    }
}

Solution2

  • 解法一比较直观易懂,但实际上计算了很多次不必要的迭代。因为当两根线往中间靠拢的时候,每次都是选择的最短那条边往中间移动,对于那些移动后比移动之前还要短的边实际上可以不需要考虑,只需要考虑移动后比移动前高的边就行,因为往中间移动的时候宽变窄了,只有较短的边变高之后才有可能使得整个的矩形面积最大。这种思路的代码如下:
        int result = 0;
        int n = height.length;
        for(int i=0,j=n-1;i<j;){
            result = Math.max(result,Math.min(height[i],height[j])*(j-i));
            if(height[i]<height[j]){
                int k = i+1;
                while(k<j&&height[k]<=height[i]) k++;//将较短边往中间移动,知道找到一个比现有边更高的边
                i = k;
            }
            else{
                int k = j-1;
                while(k>i&&height[k]<height[j]) k--;
                j = k;
            }
        }
        return result;

Solution3

  • 解法2在运行的时候比解法1更加高效,但是代码却没有解法一那么直白浅显。这里有一种不一样的代码实现,思想仍然是一样的。
public class Solution {
    public int maxArea(int[] height) {
        int result = 0;
        for(int i=0,j=height.length-1;i<j;){
            int h = Math.min(height[i],height[j]);//先找到最短的边
            result = Math.max(result,h*(j-i));
            while(i<j&&height[i]<=h) i++;//虽然有两个while循环,实际每次迭代的时候都只有最短边在移动直到比当前边高
            while(i<j&&height[j]<=h) j--;
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值