看到这道题之后的第一个想法就是暴力,你有你的双指针我有我的两个for当然结果是显而易见的超时了。
暴力超时法:
int len = height.size()-1;
int ans = 0;
for(int i = 0;i<=len;i++)
{
for(int j = i+1;j<=len;j++)
{
//获取i和j坐标的最小值之后用i与j之间的距离乘以最小值即为最多盛水数
int flag = min(height[i],height[j]);
int t = flag * (j - i);
ans = max(ans,t);
}
}
return ans;
双指针法:
class Solution {
public:
int maxArea(vector<int>& height) {
//右指针指向数组的最右端
int len = height.size()-1;
//左指针指向数组的最左端
int x = 0;
int ans = 0;
while(x<len)
{
int flag = min(height[x],height[len]);
int t = flag * (len-x);
ans = max(ans,t);
//当x坐标的值小于len坐标的值时让左指针x++
if(height[x]<height[len])
x++;
else
len--;
}
return ans;
}
};