11. Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
用两个指针从数组的左边和右边开始,向中间搜索。依据的理由有两点:
1、因为一开始底边长就已经是最大,两个指针向中间移动的时候,底边长只会变短,因此如果此时面积要变大的话,只能是两条高中的最短者比移动前的最短高更高,
2、因此,每次选择移动左指针还是右指针,优先选择当前高度最短的那个,以期寻找到更高的边。如果此时选择移动当前高度最高的那个,就有可能跳过了最优解。
直观的解释是:容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以我们从长度最长时开始递减,然后寻找更高的线来更新候补;
class Solution {
public:
int maxArea(vector<int>& height) {
int left= 0;
int right = height.size() - 1;
if(right == 0)
{
return 0;
}
int dis = right - left;
int maxHeight= min(height[left], height[right]);
int res = dis*maxHeight;
while(left < right)
{
if(height[left] < height[right])
{
left++;
}
else
{
right--;
}
dis = right - left;
maxHeight= min(height[left], height[right]);
res = max(dis*maxHeight,res);
}
return res;
}
};