题目:11. 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 iis 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.
题意:
给一个包含非负整数的数组,以数组中元素的值为容器的高,两个数组下标距离为长,求矩形容器的最大面积。输入数组最少包含两个数。
分析:
- 第一种思路:暴力遍历所有情况,输出最大值。实现见Code1.
- 第二种思路:通过观察可以看出,矩形容器的高度总是被最短的那个数限制到,因此,可以改变较小的一端。实现见Code2.
Code1 & C++
class Solution {
public:
int maxArea(vector<int>& height) {
int max=0, len=height.size();
for(int i=0;i<len-1; ++i){
for(int j=i+1; j<len; ++j){
int tmpHeight = height[i]>height[j]?height[j]:height[i];
if(max < tmpHeight*(j-i)){
max = tmpHeight *(j-i);
}
}
}
return max;
}
};
结果:
Runtime: 1520 ms, faster than 18.17% of C++ online submissions for Container With Most Water.
Memory Usage: 10 MB, less than 64.39% of C++ online submissions for Container With Most Water.
Code2 & C++
auto s=height.begin(), e = height.end()-1;
int maxA = 0;
while(s!=e){
int tmp,h=e-s;
if(*s<*e){
tmp = *s;
++s;
}else{
tmp = *e;
--e;
}
maxA = max(maxA, tmp*h);
}
return maxA;
这里 设置了两个端点分别位于起始处和终止处。两端同时向中间较大的值靠拢。
结果
Runtime: 20 ms, faster than 98.54% of C++ online submissions for Container With Most Water.
Memory Usage: 10.1 MB, less than 17.25% of C++ online submissions for Container With Most Water.
Code2 & Python
class Solution:
def maxArea(self, a: 'List[int]') -> 'int':
i,j = 0, len(a)-1
maxA, tmp = 0, 0
while i<j:
if a[i]>a[j]:
tmp = a[j]
j-=1
else:
tmp = a[i]
i+=1
area = tmp *(j-i+1)
maxA = area if area>maxA else maxA
return maxA
结果:
Runtime: 48 ms, faster than 99.77% of Python3 online submissions for Container With Most Water.
Memory Usage: 13.5 MB, less than 90.54% of Python3 online submissions for Container With Most Water.
第二种方法 动画展示,能加形象的理解这一过程。