知识点:双指针遍历大大减少不必要的比较和计算
方法1:Brute Force(执行时间惨不忍睹,共进行n(n-1)/2次比较)
class Solution { public: int maxArea(vector<int>& height) { int res=0; for(int i=0;i<height.size();i++) for(int j=i+1;j<height.size();j++) res = max(res,min(height[i],height[j])*(j-i)); return res; } };
方法2:双指针法( O(n) )
参考https://segmentfault.com/a/1190000008824222
class Solution { public: int maxArea(vector<int>& height) { int res=0; int l=0,r=height.size()-1; while(l!=r) { res = max(res,min(height[r],height[l])*(r-l)); if(height[l] > height[r]) r--; else l++; } return res; } };