盛水最多的容器
本题很明显用双指针法
而且要明确一点,本题是要返回一个面积值,所以我们只需要先设定一个初始面积值,后面求得的面积值不断与其相比较,取最大就好。
双指针,分别指向数组的两端。
把数字具象成一根根柱子,我们的指针柱子之前游走。
一个容器能盛水多少,取决于最短的那根柱子有多高,所以我们需要尽力移动指向较短柱子的指针,不断换长柱子,就能增大面积。
为了方便比较,单独写一个求面积的函数。
int Area(int bottom, int h1, int h2)
{
if (h1 > h2)
return bottom * h2;
else
return h1 * bottom;
}
int maxArea(int* height, int heightSize) {
int left = 0, right = heightSize - 1;
int bottom = right - left;
int area=Area(bottom,height[left],height[right]);
int res = area;
while (left < right)
{
bottom = right - left;
area = Area(bottom, height[left], height[right]);
if (area > res)
res = area;
if (height[right] < height[left])
right--;
else
left++;
}
return res;
}