一。题目:
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 linei 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.
题意:给一组数组整数 a1, a2, ..., an,,作为与Y轴平行的直线。这些竖线与X轴合成一个容器,求出该容器最大的容量思路1:暴力解法。外围循环从0至size-1。内重循环1至size-1,在此过程中不断更新比较最大容量
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int maxCap = 0;
while (left<height.size())
{
int right = height.size() - 1;
for (int i = right; i >= 0;i--)
{
int tempMax = 0;
if (height[left]<height[i])
{
tempMax = height[left] * (i - left);
}
else
{
tempMax = height[i] * (i - left);
}
if (maxCap < tempMax)
{
maxCap = tempMax;
}
}
left++;
}
return maxCap;
}
};
其结果就是超时。。。
思路2(这个我没想出来,想过对撞指针不知道怎么处理,智商捉急啊):
对撞指针:首尾两个索引的值取最小的为容器的高度,可以计算出此时的容量,当左边的值小于等于此时容器的高度直接跳过(表示这些值都在容量内),直到找到一个大于容量高度的值停下来。同样的右边也如此(尽管上一次容器的高度取的是左右两侧小的值,但是当两者相等时就需要在右侧找一个大于当前容器高度的值)。再重新计算容器新的高度,同时计算此时的容量,更新最大容量。
class Solution {
public:
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while (i < j) {
int h = min(height[i], height[j]);
water = max(water, (j - i) * h);
while (height[i] <= h && i < j) i++;
while (height[j] <= h && i < j) j--;
}
return water;
}
};