1.Question
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.
2.Code
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size()-1;
int max_area = 0;
while(left < right)
{
int height_left = height[left];
int height_right = height[right];
max_area = max( max_area, min(height_left, height_right) * (right - left) );
if(height_left > height_right) right--;
else left++;
}
return max_area;
}
};
3.Note
a. 最简单的思路就是用两个for进行遍历。但是复杂度比较高。
b. 另一个思路就是由两边往中间走,寻找最大的积水面积。用left和right表示两边的指针,当距离不停缩小的时候,只有边缘的高度越高,积水面积才有可能越高。那么就把缩小步长设为1,如果最新的积水面积更大则更新max_area,否则依然保留最高的边,另一边往中间靠。直到遍历结束即left = right。