Two Pointers O(n)
面积 = 宽(min of two heights) X 长(the distance between two heights)
1.保证长或宽从大到小:宽比较难从大到小排因为heights都是乱序的;长倒是可以,从两侧的heights开始考虑
2.在保证长是从大到小的情况下,只需要保证宽尽量高就行了:不断替换较矮的那个height
Python
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height)-1
res = 0
while l<r:
res = max(res, min(height[l], height[r])*(r-l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return res
C++
class Solution {
public:
int maxArea(vector<int>& height) {
int l=0, r=height.size()-1;
int res = 0;
while(l<r){
int area = height[l]<height[r] ? (r-l)*height[l++]:(r-l)*height[r--];
res = max(res, area);
}
return res;
}
};