文章目录
- 1 暴力(超时)
- 2 双指针(双指针 两边中高度最低的指针靠近)
1 暴力(超时)
代码语言:javascript
复制class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
int size = height.size();
for (int i = 0; i < size; i )
for (int j = size - 1; j > i; j--) {
int maxCoArea = (j - i) * min(height[i], height[j]);
if (maxCoArea > maxarea)
maxarea = maxCoArea;
}
return maxarea;
}
};
2 双指针(双指针 两边中高度最低的指针靠近)
代码语言:javascript
复制class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
int left = 0, right = height.size() - 1;
while (left < right) {
int coarea = (right - left) * min(height[left], height[right]);
if (coarea > maxarea) maxarea = coarea;
// 两边中高度最低的指针靠近1步
if (height[left] < height[right]) left ;
else right--;
}
return maxarea;
}
};