相关问题
Discription
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
Note: You may not slant the container and n is at least 2.
思路
双指针:用两个指针分别表示容器的左边界 left 和右边界 right。
初始 left 指向最左,right 指向最右。
考虑如下两点事实:
- 容器的盛水量取决于短的边界高度 min(height[left], height[right]) 以及水平长度 right - left ;
- 随着 left 向右移动或者 right 向左移动,水平长度必然减小;
故只有提高短边界的高度 min(height[left], height[right]) 才有肯能提高盛水量。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0, right = height.size() - 1;
int max_area = min(height[left], height[right]) * (right - left);
while (left < right)
{
int min_h = min(height[left], height[right]);
if (height[left] == min_h) // 找到瓶颈
while (left < right && height[left] <= min_h) left++;
else
while (left < right && height[right] <= min_h) right--;
if (left < right)
{
int area = min(height[left], height[right]) * (right - left);
max_area = max(area, max_area);
}
else
break;
}
return max_area;
}
};