Container With Most Water
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.
给定 n 个非负整数 a1, a2, ..., an,以元素下标为横坐标组成坐标点 (i, ai),过这些点做垂直于x轴的垂线,找出两根线和横坐标一起组成一个容器,使容器能存储最多的水。
注意:不能倾斜容器。
分析:
法1:从左向右逐个计算两根线组成的容器,总是记录最大的值。复杂度为 O(n²),出现 Time Limited.
法2:从两端向中间查找计算并记录最大值,如果存在更大的值,只有可能是存在高度比当前最小高度大的值;时间复杂度为 O(n).
int maxArea(int* height, int heightSize) {
int lside = 0, rside = heightSize-1;
int smallHeight = 0;
int area = 0, mArea = 0;
if(!height)//空
{
return 0;
}
while(lside < rside)
{
smallHeight = (height[lside] < height[rside])?height[lside]:height[rside]; //取较低的高度,决定水位
area = (rside - lside)*smallHeight;
if(area > mArea)
{
mArea = area;
}
//从两端向中间比较,比两端大的只可能是最小边更大的边组成的面积
if(height[lside] < height[rside])
{
++lside;
}
else
{
--rside;
}
}
return mArea;
}