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个高度不同的数作为为Y坐标,以序列1到n为X坐标,这样的点(i,ai)分别和(i,0)组成的线段有n条,从中选取两条,以最短的一条为高,线段在X轴上的距离为宽,求最大的矩形面积。
时间复杂度为O(n)
解题思路:两条线段,哪个短,就换哪个
int maxArea(int* height, int heightSize) {
int i,j,max,area;
i=0;
j=heightSize-1;
max=0;
while(i<j){
area=(height[i]>height[j]?height[j]:height[i])*(j-i);
if(area>max){
max=area;
}
if(height[i]>height[j]){
j--;
}else{
i++;
}
}
return max;
}
针对一道经典的算法题目,介绍了一种高效求解最大盛水量的方法。该算法通过双指针技巧实现了O(n)的时间复杂度,不断调整左右边界来寻找最大面积。
2319

被折叠的 条评论
为什么被折叠?



