题目:
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 and n is at least 2.
翻译:给定n个非负整数a1,a2,...,an,其中每个代表一个点坐标(i,ai)。n个垂直线段例如线段的两个端点在(i,ai)和(i,0)。找到两个线段,与x轴形成一个容器,使其包含最多的水。
备注:你不必倾倒容器。
这道题一开始没明白什么意思,想了很久,才想通,大致就是给你N条线段,例如a1,a2,a3,...,an,下标代表这条线段的位置,an代表这条线段的高度,找出两条线段,一高度最小的那条线段高度为长,两条线段的距离为宽,使这两条线段围成的正方形面积最大。比如 a1 = 10, a2 = 5, a3 = 6,则两两组合所围成的正方形面积分别为 (a1,a2) = 5 * (2 - 1) = 5, (a1,a3) = 6 * (3 - 1) = 12,(a2,a3) = 5 * (3 - 2) = 5,则该三条线段所围成的最大面积为12,则该题解为12。
解决这种问题我们可以通过暴力求解法,两两组合求出最大解,其算法为:
class Solution
{
public:
int maxArea(vector<int> &height)
{
int size = height.size();
if (size <= 0)
return 0;
int result = 0;
int tmpResult = 0;
for (int i = 0; i < size-1; i++)
{
for (int j = i+1; j < size; j++)
{
if (height[i] >= height[j])
{
tmpResult = height[j] * (j - i);
}
else
{
tmpResult = height[i] * (j - i);
}
if (result < tmpResult)
result = tmpResult;
}
}
return result;
}
};
该算法的时间复杂度为O(n*n),当然,我们提交后会显示Time Limit Exceeded;
另一个算法,如下所示:
class Solution
{
public:
int maxArea(vector<int> &height)
{
int i = 0;
int j = height.size() - 1;
int ret = 0;
while(i < j)
{
int area = (j - i) * min(height[i], height[j]);
ret = max(ret, area);
if (height[i] <= height[j])
i++;
else
j--;
}
return ret;
}
};
该算法的时间复杂度时O(n),其主要思想时从两边开始计算长方形面积,从线段最短的那边开始移动,每移动一次,就计算一次长方形面积,直到计算出最大面积。(只能移动最短的那条线,因为移动大的那条线,面积就更小了,那就找不到最大了。所以每次都是移动短的那条。