LeetCode:盛最多水的容器

刷题神器:LeetCode官方网站

一、题目还原

给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
Q11题目图片
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入:[1,8,6,2,5,4,8,3,7]
输出:49

二、解题思路

Solution 1:暴力循环法
① 两层循环逐一计算组成面积大小,取最大值返回

Solution 2:中心靠近
① 以横坐标最左侧left和最右侧right为起始点计算面积
② 如果左侧的高度低,则向右移动left++,反之左移right–
③ 返回最大面积

三、代码展示

① main函数

public static void main(String[] args) {
   int[] height  = {1,8,6,2,5,4,8,3,7};
    System.out.println("maxArea == "+maxArea(height));
    System.out.println("maxArea2 == "+maxArea2(height));
}

② 暴力法方法函数

//暴力法
public static int maxArea(int[] height) {
    if(height.length < 2){
        return 0;
    }
    int result = 0;
    Map<Integer,Integer> map = new HashMap<Integer, Integer>();
    for(int i = 0 ; i < height.length ; i ++){
        for(int j = i+1 ; j < height.length ; j ++) {
            result = Math.max(result,(j - i) * Math.min(height[i],height[j]));
        }
    }
    return result;
}

控制台输出:

maxArea == 49

Process finished with exit code 0

② 中心靠近方法函数

//中心靠近
public static int maxArea2(int[] height) {
    //EdgeCase
    if(height.length < 2){
        return 0;
    }

    int left = 0;
    int right = height.length - 1;

    int result = 0;
    while(left < right){
        result = Math.max(result,(right - left) * Math.min(height[right],height[left]));
        if(height[left] < height[right]){
            left ++;
        }else{
            right --;
        }
    }
    return result;
}

控制台输出:

maxArea2 == 49

Process finished with exit code 0
四、自我总结

LeetCode第十一题,难度为中等。做了前十题之后,博主发现本题和之前做过的题目都很类似,虽然应用场景不一样,但是所使用的算法逻辑倒是十分相近。这道题和判断回文字符的思想就非常接近,在那道题当中使用的是中心扩散,这道题使用的中心靠近。
Q11提交记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值