题目描述:
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 and n is at least 2.
分析:
题意:在二维平面的相等间隔位置摆放不同高度的垂直线,我们需要找到两根垂直线,使得他们围成的面积最大(长为X轴间隔距离,宽为Y轴较短垂直线高度)。
思路:这题采用双指针法。假设垂直线数量为n,那么我们初始化指针left = 0、right=n-1(即指向第一条、最后一条垂直线),得到两者较短高度,计算获得面积。如果left指针右边的垂直线高度比当前最短高度低,则left右移(因为left右移之后,left、right的X轴间隔变小,要想获得更大面积,高度必须增加);同理,如果right指针左边的垂直线高度比当前最短高度低,则right左移。与此同时,更新最大面积。
时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
// two pointers
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
// Exceptional Case:
if(n <= 1){
return 0;
}
int ans = 0;
int left = 0, right = n - 1;
while(left < right){
// debug
// cout << "left: " << left << ", right: " << right << endl;
int min_height = min(height[left], height[right]);
ans = max(ans, min_height * (right - left));
while(left <= n - 2 && height[left] <= min_height){
left++;
}
while(right >= 1 && height[right] <= min_height){
right--;
}
}
return ans;
}
};