https://leetcode.com/problems/container-with-most-water/
题目:
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.
思路:
考虑从边界向里缩减范围。最重要的是注意到,假设现在边界的height是a和b,那么想在内部有别的点能比a、b框成的体积大,那么这个点一定得比a、b中的最小者大。所以不断从边界height较小的点向内缩减,直到内部为空。
只需遍历数组一次,所以复杂度为O(n)。
AC代码:
class Solution {
public:
int maxArea(vector<int>& height) {
int i,j,n=height.size(),a=,b=n-,contain=min(height[],height[n-])*(n-);
while(a<b){
if(height[a]<height[b]){
for(i=a;i<b;i++){
if(height[i]>height[a])
break;
}
if(min(height[i],height[b])*(b-i)>contain){
contain=min(height[i],height[b])*(b-i);
}
a=i;
}
else{
for(j=b;j>a;j--){
if(height[j]>height[b])
break;
}
if(min(height[j],height[a])*(j-a)>contain){
contain=min(height[j],height[a])*(j-a);
}
b=j;
}
}
return contain;
}
};