- 题目: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.
- 暴力解法(o(n*n))
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
class Solution{
public:
int maxArea(vector<int> &height){
int res=0,n=height.size();
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
int tmp=(j-i)*min(height[i],height[i+1]);
if(res<tmp)
res=tmp;
}
return res;
}
};
int main()
{
int n,t;
vector<int> test;
Solution s;
while(cin>>n){
for(int i=0;i<n;i++){
cin>>t;
test.push_back(t);
}
cout<<s.maxArea(test)<<endl;
}
return 0;
}
- 双指针(O(n))
两个指针分别从后向前移动,,两个指针分别表示容器的左右界,每次迭代用当前的容量更新最大容量,然后把高度小的边界的指针往中间移动。
证明:
/*
*/
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
class Solution{
public:
int maxArea(vector<int> &height){
int res=0,n=height.size();
int left=0,right=n-1;
while(left<right){
res=max(res,(right-left)*min(height[left],height[right]));
if(height[left]<height[right])
left++;
else right--;
}
return res;
}
};
int main()
{
int n,t;
vector<int> test;
Solution s;
while(cin>>n){
for(int i=0;i<n;i++){
cin>>t;
test.push_back(t);
}
cout<<s.maxArea(test)<<endl;
}
return 0;
}