一.题目描述
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.
二.我的解题思路
这套题目的意思还是很明确的,假定选取ai,aj,,那么就有area = (j-i) * min(ai,aj)。现在我们就是要从n(n-1)/2个i,j组合中找出area最大的那个。
最直观的想法就是建立二重循环,遍历所有这n(n-1)/2个组合的area,但是这样做是肯定不满足时间复杂度要求的。接下来就是思考如何进行优化,想了一会发现难以像之前遇到的题目那样进行优化。因为优化的前提是不同组合之间是有联系的,并且可以利用这个联系来简化问题。但是对于这道题目,不同组合之间是独立的,因此难以找到较好的优化方法。
想不到较好的优化思路,下一步就是想想可否利用经典的算法思想。针对这道题目,能降低时间复杂度的只有贪心算法了。采用贪心的策略,设置两个指针,一头一尾,每次取两边围栏最矮的一个推进,希望获取更多的水。最后写出的程序非常简单:
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0;
int j = height.size() - 1;
int res = 0;
while(i < j)
{
int area = (j - i) * min(height[i], height[j]);
res = max(res, area);
if (height[i] <= height[j])
i++;
else
j--;
}
return res;
}
};
个人理解使用贪心算法是有风险的,因为贪心算法并没有考虑全局的所有情况,只是每次选取最理想的选择。像之前看到的决策树算法,用的也是贪心的策略,就容易出现过拟合问题。