题目:
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.
给定非负整数组a1, a2, ..., an,,每一个代表坐标点(i, ai)。坐标点(i, ai) 和 (i, 0)形成了一条垂直于 x 轴的线段,找到两条这样的线段与 x 轴形成一个容器,使得容器能装最大容量的水。注意:不能倾斜容器。
思路:
两个指针,一个指向头一个指向尾,前面的指针向后移动,后面的指针向前移动。
代码:
class Solution {
public:
int maxArea(vector<int> &height)
{
int result = 0;
int begin = 0 , end = height.size() - 1;
while(begin < end)
{
result = max(result,(end - begin) * min(height[begin] , height[end]));
if(height[begin] < height[end])
{
do
{
begin++;
}
while(begin < end && height[begin-1] >= height[begin]);
}
else
{
do
{
end--;
}
while(begin < end && height[end] <= height[end+1]);
}
}
return result;
}
};
用while替换do while:
class Solution {
public:
int maxArea(vector<int> &height)
{
int result = 0;
int len = height.size();
if(len <= 1)
return 0;
int left = 0 , right = len - 1;
while(left < right)
{
result = max(result , min(height[left] , height[right]) * (right-left));
if(height[left] < height[right])
{
left++;
while(left < right && height[left-1] >= height[left])
left++;
}
else
{
right--;
while(left < right && height[right] < height[right+1])
right--;
}
}
return result;
}
};