LeetCode:盛最多水的容器

方法一:

java 复制代码
class Solution {
    public int maxArea(int[] height) {
        //定义左右指针
        int left = 0;
        int right = height.length - 1;
        //初始化最大储水量
        int maxWater = 0;
        //定义条件,只要左指针 < 右指针(两者没相遇)就继续
        while(left < right){
            //计算当前储水量
            int currentWideth = right - left;
            int currentHeight = Math.min(height[left],height[right]);
            int currentWater = currentWideth * currentHeight;

            maxWater = Math.max(currentWater,maxWater);
            //指针移动找最大的currentHeight
            if(height[left] < height[right]){
                left++;
            }else{
                right--;
            }
        } 
        return maxWater;
    }
}

方法二(省时间):

java 复制代码
class Solution {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int maxWater = 0;

        while(left < right){
            int hLeft = height[left];
            int hRight = height[right];

            int minHeight = hLeft < hRight ? hLeft :hRight;
            int currentWater = minHeight * (right - left);
            if(currentWater > maxWater){
                maxWater = currentWater;
            }

            //这里面又一次加上了,left < right,目的是防止连续的前进导致数组越界报错
            if(hLeft < hRight){
                while(left < right && height[left] <= minHeight){
                    left++;
                }
            }else{
                while(left < right && height[right] <= minHeight){
                    right--;
                }
            }
        }
        return maxWater;
    }
}

第二段代码更省时间主要体现在以下几方面:

第一,第二段代码直接在if-else里面的while循环选高的柱子,而第一段代码不仅每次都要读左右高度计算面积还要读左右高度进行比较选高的柱子,第二段代码省下了第一段代码中每次都要读左右高度用于计算面积这一步的读取。

第二,去掉第一段代码中的Math.min()和Math.max(),改成了if-else和三目运算符,这是底层机器指令,没有任何方法调用,cpu执行快。

第三,第一段代码无论碰到柱子是高是矮都进行一次面积计算,而第二段代码在while循环中进行柱子选择,只有遇到比原来高的柱子才进行面积计算,减少了大量无意义的计算。

相关推荐
不爱吃炸鸡柳17 小时前
单链表专题(完整代码版)
数据结构·算法·链表
CylMK18 小时前
题解:AT_abc382_d [ABC382D] Keep Distance
算法
Dfreedom.18 小时前
计算机视觉全景图
人工智能·算法·计算机视觉·图像算法
Morwit18 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
py有趣18 小时前
力扣热门100题之岛屿的数量(DFS/BFS经典题)
leetcode·深度优先·宽度优先
无小道19 小时前
算法——暴力+优化
算法·优化·暴力
Free Tester19 小时前
如何判断 LeakCanary 报告的严重程度
java·jvm·算法
zyq99101_119 小时前
DFS算法实战:经典例题代码解析
python·算法·蓝桥杯·深度优先
智者知已应修善业20 小时前
【51单片机单按键切换广告屏】2023-5-17
c++·经验分享·笔记·算法·51单片机
广州灵眸科技有限公司20 小时前
为RK3588注入澎湃算力:RK1820 AI加速卡完整适配与评测指南
linux·网络·人工智能·物联网·算法