力扣:盛水最多的容器(leetcode)

在这里插入图片描述

class Solution {
    
    
    public int maxArea(int[] height) {
    
    
   //如果此数值没有数,或者只有一个数,则构不成面积直接返回-1
     if(height.length<=1) return -1;
     //从两头开始遍历
     int i= 0,j=height.length-1 ,res=0;
     while(i<j)
     {
    
    
     //找短板做乘积
         int h = Math.min(height[i],height[j]);
         //记录面积,发现更大面积则更新,若没有则不变
         res =Math.max(res,h*(j-i));
         //短的一方移动(因为短的一方下次更可能变长,使面积增大)
         if(height[i]<height[j])
         {
    
    ++i;} else --j;
     }
     return res;

来着力扣:https://leetcode-cn.com/problems/container-with-most-water/submissions/

猜你喜欢

转载自blog.csdn.net/weixin_43889487/article/details/121104246