1、最简单的思路就是暴力求解,采用两次循环,时间复杂度为O(n^2)。
代码如下:
class Solution {
public:
int maxArea(vector& height) {
int length = height.size();
int max = 0;
int temp = 0;
for(int i = 0; i < length; i++){
for(int j = i+1; j < length; j++){
temp = (j-i) * min(height[i], height[j]);
if(temp > max)
max = temp;
}
}
return max;
}
};
2、对撞指针的方法
代码如下:
class Solution {
public:
int maxArea(vector& height) {
int max = 0;
int temp = 0;
int left = 0;
int right = height.size() - 1;
for( ; left < right; ){
temp = (right - left) * min(height[left], height[right]);
if(temp > max)
max = temp;
if(height[left] < height[right]) //左边是“短板”
left++;
else //右边是“短板”
right--;
}
return max;
}
};