题解:
使用双指针left和right,初始时分别位于height数组的左右两侧。
移动left和right指针,保证容量最大:
假设height[left]和height[right]中较大的为high,较小的为low。如果选择high指针向内侧移动(用next指针表示),容器宽度减小,容器高度有两种情况:height[next]>=height[low],高度不变;height[next]<height[low],高度减小,综上容量一定减小。如果选择low指针向内侧移动,容器宽度减小,容器高度有两种情况:height[next]>=height[high],高度增大;height[next]<height[low],高度可能增大也可能减小(height[next]<height[low]就减小,height[next]<height[low]就增大),综上容量可能增大也可能减小。
根据上述分析,如果移动较大的指针,那么容量一定是减小的;如果移动较小的指针,那么容量可能增大页可能减小。因此选择每次移动较小的指针,直到两个指针相遇,记录该过程中最大容量。
class Solution {
public:
int maxArea(vector<int>& height) {
int left=0,right=height.size()-1;
int capacity=(right-left)*(min(height[left],height[right]));
while(left<right)
{
if(height[left]>=height[right]) right--;
else left++;
capacity=max(capacity,(right-left)*(min(height[left],height[right])));
}
return capacity;
}
};