Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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.
知道原理就是很简单的程序。两边搜索,短板往里走。因为往里走,代表宽度减小,那么宽度小的时候,只有遇上更高的高度才能组成更加大的container。
int maxArea(vector<int> &height)
{
int area = 0;
int i = 0, j = height.size()-1;
while (i<j)
{
area = max(area, (j-i)*min(height[i], height[j]));
(height[i] > height[j])? j--:i++;
}
return area;
}
本文介绍了一个寻找二维平面上由两条垂直线与x轴形成的能容纳最多水的最大容器的算法。该算法采用双指针策略从两端开始逐步向中间逼近,确保了较高的效率。
9万+

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



