LeetCode-11. 盛最多水的容器

Posted 一只猫的旅行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-11. 盛最多水的容器相关的知识,希望对你有一定的参考价值。

给定 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


解法1:暴力破解
import java.lang.Math;
class Solution {
    public int maxArea(int[] height) {
        int max = Integer.MIN_VALUE;
        for(int i=0; i<height.length; i++){
            for(int j=i+1; j<height.length; j++){
                int x = j - i;
                int y = Math.min(height[i],height[j]);
                max = Math.max(max,x*y);
            }
        }
        return max;
    }
}

 解法2:优化

import java.lang.Math;
class Solution {
    public int maxArea(int[] height) {
        int max = Integer.MIN_VALUE;
        int i = 0;
        int j = height.length-1;
        while(i<j){
            int x = j - i;
            int y = Math.min(height[i],height[j]);
            max = Math.max(max,x*y);
            if(height[i]>height[j]){
                j--; 
            }else{
                i++;
            }
        }
        return max;
    }
}

ps: Math.min()   Math.max()  自己写 if()else() 会更快,用的时间更少。

以上是关于LeetCode-11. 盛最多水的容器的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 11. 盛最多水的容器

算法leetcode|11. 盛最多水的容器(rust重拳出击)

算法leetcode|11. 盛最多水的容器(rust重拳出击)

LeetCode 11 盛最多水的容器

[leetcode] 11.盛最多水的容器

leetcode——11.盛最多水的容器