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.
思路:
1. 第一种思路,就是先从左往右遍历,保存从0到i之间最大值的位置,然后在从右往左遍历,保存从height.size()-1到i之间最大值的位置。经过两次遍历,在每个位置都找到了从这个位置往左看的最高的挡板,同时找到从这个位置往右看的最高的挡板,就可以在每个位置处用计算最大装水的面积,然后取最大的面积即可!
2. 题目的意思理解错误。这个题是找任意两块挡板,最短的挡板×挡板距离得到的面积最小。上面的方法,适合求两个挡板之间不能有比这个挡板都高的挡板存在的情况!!
3. 简单粗暴的方法是:枚举所有两两组合,然后计算面积,这样的复杂度就是o(n^2)。一般这类题,都希望有o(n)的复杂度。
4. 如何降低复杂度?用two-pointer:把两块挡板初始化放在left=0,right=height.size()-1的位置,然后求面积,然后比较在left和right的高度,高度小的,则对应的挡板往内测移动。从而可以减去很多不必要的操作。这个需要证明:https://discuss.leetcode.com/topic/503/anyone-who-has-a-o-n-algorithm/3 关键思想是:用反证,如果不移动低的这一块,则移动高的,只要证明移动高的所得到的面积一定小于当前的面积,求最大值的话,就没必要去尝试比已知的值还小的情况:移动高的,距离减少,如果移动之后高度比低的那一块还高,装水的多少仍由低的那一块决定,但是距离变小,所以面积也变小;如果移动后高低比低的那一块还低,那么不但距离变小,装水高度也会变低,总面积也变小。所以,用two pointer可以减少不必要的计算,从而降低复杂度!!
//方法1:two pointer
class Solution {
public:
int maxArea(vector<int>& height) {
//two pointer:
int left=0,right=height.size()-1;
int maxArea=0;
while(left<right){
maxArea=max(maxArea,min(height[left],height[right])*(right-left));
height[left]<height[right]?left++:right--;
}
return maxArea;
}
};