leetcode#11盛水的容器:为什么要用else

gfttwv5a  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(305)

leetcode#11盛水的容器
https://leetcode.com/problems/container-with-most-water/
给定n个非负整数a1,a2,…,an,其中每个表示坐标(i,ai)处的一点。画n条垂直线,使线i的两个端点位于(i,ai)和(i,0)。找出两条线,这两条线和x轴一起构成一个容器,使容器中的水最多。
注意不要使容器倾斜。
我的代码是:

class Solution {
    public int maxArea(int[] height) {
        int l=0, r=height.length-1;
        int ans=0;
        while(l<r){
            int area= Math.min(height[l],height[r])*(r-l);
            ans=Math.max(ans,area);
            if(height[l]<=height[r]){
                l++;
            }
            if(height[l]>height[r]){
                r--;
            }
        }
        return ans;
    }
}

然而,正确的答案是:

class Solution {
    public int maxArea(int[] height) {
        int l=0, r=height.length-1;
        int ans=0;
        while(l<r){
            int area= Math.min(height[l],height[r])*(r-l);
            ans=Math.max(ans,area);
            if(height[l]<=height[r]){
                l++;
            }
            else{
                r--;
            }
        }
        return ans;
    }
}

它们之间唯一的区别是我使用if(height[l]>height[r]),而不是else
但在我的代码中,输入:[1,8,6,2,5,4,8,3,7]输出:40预期:49
我不知道为什么,它们之间有什么区别。

1l5u6lss

1l5u6lss1#

注意,如果第一个条件有效,变量 l 在计算第二个条件之前增加,这意味着您要比较两个条件中的不同数组项。因此,在某些情况下,这两个条件都是正确的

相关问题