老办法遍历肯定是超时 无需尝试.
解决思路为取两侧的挡板,高为a,b.因为是两侧了,所以距离肯定是最远的.接下来从a,b中高度低的一侧向里找,遇到比a高的就比较容积,当a,b大小发生改变时候重新判断,保证遍历方向是从a,b中低的一侧向里走就好.
c# code
public class Solution
{
public int MaxArea(int[] height)
{
if(height.Length<2)
return 0;
int max=Math.Min(height[0],height[height.Length-1])*(height.Length-1),i=0,j=height.Length-1;
int a=height[i],b=height[j];
while(i<j)
{
bool flag=a<b;
if(flag==true)
{
i++;
if(height[i]>a)
{
a=height[i];
max=max>Math.Min(a,b)*(j-i)?max:Math.Min(a,b)*(j-i);
}
}
else
{
j--;
if(height[j]>b)
{
b=height[j];
max=max>Math.Min(a,b)*(j-i)?max:Math.Min(a,b)*(j-i);
}
}
}
return max;
}
}