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

相关推荐
phltxy7 小时前
C语言操作符详解
java·c语言·算法
aqiu1111117 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考8 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾9 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研10 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183111 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974811 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye11 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展