【LeetCode】盛最多水的容器
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入: [1,8,6,2,5,4,8,3,7] 输出: 49
这个题总共有两个思路,其中一个是用双重for循环来暴力求解,这样的时间复杂度会是O(n^2),但是这种方法在LeetCode中提交的话,其中一种极端情况会超出时间限制,所以我们用另一种方法:即定义了数组开头大小和数组结尾大小两个指针,两者向更小的一方移动,这样可以减少遍历的空间。下面给出AC的可运行代码(为了可运行,稍许改动):
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int maxArea(int height[],int len) {
int maxn=0,start=0,end=len-1;
while(start<end){
int h=min(height[start],height[end]);
if((end-start)*h>maxn)
maxn=(end-start)*h;
if(height[start]<height[end])
start++;
else
end--;
}
return maxn;
}
int main(){
int a[1024],len;
cin>>len;//数组大小
for(int i=0;i<len;i++){
cin>>a[i];
}
cout<<maxArea(a,len);
return 0;
}
在LeetCode中提交的代码如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int maxn=0,start=0,end=height.size()-1;
while(start<end){
int h=min(height[start],height[end]);
if((end-start)*h>maxn)
maxn=(end-start)*h;
if(height[start]<height[end])
start++;
else
end--;
}
return maxn;
}
};