Leetcode_11_乘最多水的容器
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
示例 1:

输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int maxArea(int[] height) {
int left=0,right=height.length-1;
int maxA=0;
while(left<right){
int h = height[left]>height[right]?height[right]:height[left];
int area = h*(right-left);
maxA=maxA>area?maxA:area;
int tso = height[left]>height[right]?right:left;
if(tso==left){
left+=1;
}else{
right-=1;
}
}
return maxA;
}
}
此解法采用的是双指针法,左指针和右指针分别指向数组头和尾,每次计算出一个面积后,更新当前最小面积值,然后将值小的那一端的指针向中间移动,重叠后,返回当前最大值即为答案。
530

被折叠的 条评论
为什么被折叠?



