【从零单排leetcode】11. Container With Most Water

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

翻译:给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)。 找到两条线,其与x轴一起形成容器,使得容器包含最多的水。


注意:您不能倾斜容器,n至少为2。


分析:也就是计算最大容量,第一考虑是直接暴力试试看会有什么结果。

public class Solution {
    public int maxArea(int[] height) {
        int len = height.length;
        int high , max=0;
        for(int i = 1 ; i < len ; i++){
            for(int j = 0 ; j < i ; j++){
                high = (i - j)*min(height[i],height[j]);
                if(high>max){
                    max = high;
                }
            }
        }
        return max;
    }
    public int min(int a , int b){
        if(a>b)
        return b;
        else return a;
    }
}


思路是每一次计算所有下标不大于i的容量,如果有大于以前算出来的容量就替换。

然后结果是很自然的TLE。

可能扫描的方法可以优化。因为要扫描某两个数作为容器的两边,在数组左右分别设定两个指针,然后两者比较时较小的向中间移动,这样总是能够将最大的容积扫描到。以下简单证明一下,如果第3个和第10个相间的为最大容积,那么在左边到达第3个时,右边是能够因为第11个小于3而往中间移动,也就是右边移动到10,否则就会3与11之间的容积一定大于3与10,与假设矛盾了。再考虑左边与右边类似, 所以这样的O(n)算法也是可以满足的。

public class Solution {
    public int maxArea(int[] height) {
        int left = 0 , right = height.length-1;
        int con , max = 0;
        while(left < right){
            con = (right - left)*min(height[left],height[right]);
            if(con > max) max = con;
            if(height[left] > height[right]) right--;
            else left++;
        }
        return max;
    }
    public int min(int a , int b){
        if(a>b)
        return b;
        else return a;
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值