LeetCode0011-装水最多的容器

///给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
//
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/container-with-most-water
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 解题思想:
// 面积取决于短板。
// ①因此即使长板往内移动时遇到更长的板,矩形的面积也不会改变;遇到更短的板时,面积会变小。
// ②因此想要面积变大,只能让短板往内移动(因为移动方向固定了),当然也有可能让面积变得更小,但只有这样才存在让面积变大的可能性
public class Num011_containerWater {

//    暴力破解 O(N^2) 数据很多会超时
public int maxArea(int[] height) {

    int weight= height.length-1;
    int total=height.length-1;
    int max =0;int count =0;
    for(;weight>=0;weight--){
        for(int i=0;i <=total-weight;i++){
            count = weight*Math.min(height[i],height[i+weight]);
            max=Math.max(count,max);
        }
    }
    return max;
}
//方法二: 桶理论,能放多少取决于最短的那个板子
public int maxArea1(int[] height) {


    int ln = height.length-1;
    int ans =0;
    for(int i=0,j=ln;i<height.length && i<=j;){

        ans= Math.max(Math.min(height[i],height[j])*(j-i),ans);
        if(height[i]<height[j] ) { i++;} else {j--;}

    }
    return ans;
}
}

 



posted on 2021-06-30 10:20  cStream  阅读(55)  评论(0)    收藏  举报