题意: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.
题意分析:
这道题目题干已经说的很清楚了,就是找两个点求解最大面积的问题,刚开始的时候,没有考虑到时间复杂度,写了个类似这样的循环
for(int i = 0; i < n-1; i++)
for(int j = i+1; j < n;j++) {
..........
`}
提交后发现超时,仔细分析一下,这个算法是O(n^2),当数据一大的时候,超时便是很自然了。
此时得改进算法,采用两边逼近的方法,因为两边是最宽的,然后逐步往中间逼近,逼近的时候遇见比原来高度低的就跳过,这样可以大大缩短程序运行时间。
一种c++的实现如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0;
int j = height.size()-1;
int max_area = 0;
int area;
while (i < j) {
int h = find_min(height[i], height[j]);
area = h*(j-i);
max_area = find_max(area,max_area);
while(height[i] <= h && i < j)
i++;
while(height[j] <= h && i < j)
j--;
}
return max_area;
}
int find_min(int a, int b) {
if(a >= b) return b;
else return a;
}
int find_max(int a, int b) {
if(a >= b) return a;
else return b;
}
};