题目:
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.
思路:双指针,从两侧向中间逼近。当两个指针分别指向i和j的时候,假设 i < j 并且 A[i] < A[j],此时A[i] 是制约整个面积的因素。如果这个时候移动j,无论A[j-1]有多大,我们都无法获得更大的面积,因为A[i]依然制约着高度,同时宽度变小了。
class Solution {
public:
inline int min(const int& a, const int& b) {return a < b ? a : b;}
int maxArea(vector<int> &height) {
int front = 0;
int back = (int)height.size() - 1;
int max_area = INT_MIN;
while (front < back) {
int current_area = (back - front) * min(height[front], height[back]);
max_area = max_area > current_area ? max_area : current_area;
if (height[front] > height[back]) back--;
else front++;
}
return max_area;
}
};
总结:复杂度为O(n).