leetcode刷题11. 盛最多水的容器

时间:2023-03-08 23:49:22
leetcode刷题11. 盛最多水的容器

做题连接https://leetcode-cn.com/problems/container-with-most-water/submissions/

本题分为两种方法:

暴力法:

int maxArea(int* height, int heightSize) {
     int maxarea=0,s;
     for(int i=0;i<heightSize;i++)
         for(int j=i+1;j<heightSize;j++)
         {
             s=(height[i]>height[j])?height[j]:height[i];
             maxarea=(s*(j-i)>maxarea)?(s*(j-i)):maxarea;
            
         }
     return maxarea;

}

分别比较数组中边缘最小,然后面积较大值返回

头尾指针法:

int maxArea(int* height, int heightSize) {
     int maxarea=0,s,i=0,j=heightSize-1;
         while(i<j){
            
             s=(height[i]>height[j])?height[j]:height[i];
             maxarea=(s*(j-i)>maxarea)?(s*(j-i)):maxarea;
             if(height[i]<height[j])
                 i++;
             else
                 j--;
            
         }
     return maxarea;

}