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循环中进行柱子选择,只有遇到比原来高的柱子才进行面积计算,减少了大量无意义的计算。

相关推荐
XW96325810 小时前
除湿机行业组织能力与人才地图报告
大数据·服务器·网络·数据结构·数据库·人工智能
geats人山人海10 小时前
算法基础第六讲 图论
算法·深度优先·图论
Rain的Java大神之路12 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
风落青芜13 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
@陈小鱼13 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
老师我太想进步了202619 小时前
【数据结构-15】实现链式结构二叉树
c语言·数据结构
liulilittle20 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
xiangxueCode1 天前
数据结构:容器适配器之优先级队列
数据结构·优先级队列
鱼很腾apoc1 天前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习