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.
我当时的解法比较脑残,遍历隔板的高度,分别找出对应不同高度最左和最右的隔板,即可算出最大水量。
class Solution {
public:
int maxArea(vector<int>& height) {
vector<int> temp(height);
sort(temp.begin(), temp.end());
vector<int> hori; hori.push_back(temp[0]);
for (int i = 1; i < temp.size(); i++)
{
if (temp[i] == temp[i - 1])
continue;
else
hori.push_back(temp[i]);
}
int res = 0;
/*height.insert(height.begin(), 0);
height.push_back(0);*/
for (int i = 0; i < hori.size(); i++)
{
int right = 0; int left = 0; vector<int> temp;
for (int j = 0; j < height.size(); j++)
{
if (height[j] >= hori[i])
{
temp.push_back(j);
}
}
right = temp[temp.size() - 1]; left = temp[0];
if ((right - left)*hori[i] > res)
res = (right - left)*hori[i];
}
return res;
}
};
前面几个简单的例子都能过,但是接下来一个测试例子:[1,2,3,4,5...15000],巨长的排好序的数组,一看就知道超时了。。。。。
此题让人感受到了智商上的碾压,也不想翻译leetcode上答主StefanPochmann的说明了,只能说是Amazing solution。
Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don't support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left.
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0,right = height.size() - 1;
int res = 0;int h = 0;
while(left < right)
{
h = min(height[left],height[right]);
res = max(res,(right - left)*h);
while(left < right && height[left] <= h) left++;
while(left < right && height[right] <= h) right--;
}
return res;
}
};