WELCOME TO Pluto134340小行星

清风湿润,茶烟轻扬。

5.盛水最多的容器

11. 盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

示例 1:

image

输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

思路:双指针
左右各一个指针left,right。比较height[left],height[right] 哪个小移动哪个(left++)。
两重循环时间过不掉。
 1 class Solution {
 2     public int maxArea(int[] height) {
 3         int max=0,min=height[0],s=0,n=height.length;
 4         // for(int j=0;j<n-1;j++){
 5         //     for(int i=1;i<n;i++){
 6         //         s = (i-j)*Math.min(height[i],height[j]);
 7         //         max = Math.max(max,s);
 8         //     }
 9         // }
10         int left=0,right=n-1 ;
11         while(left<right){
12             s = Math.min(height[left],height[right])*(right-left);
13             max = Math.max(max,s);
14 
15             if(height[left]<=height[right]){
16                 left++;                
17             }else{
18                 right--;
19             }
20         }
21         return max;
22     }
23 }
View Code

 

posted @ 2026-01-07 16:21  Pluto134340  阅读(2)  评论(0)    收藏  举报