11. 盛最多水的容器

自己做
解1:暴力解

cpp
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int max = 0;
for(int i = 0; i < len; i++)
for(int j = 0; j < len; j++){
int s = (j - i) * min(height[i],height[j]);
if(s > max)
max = s;
}
return max;
}
};
解2:优化的暴力解

cpp
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int max = 0;
for (int i = 0; i < len; i++){
for (int j = len - 1; j > i; j--) {
if(height[j] >= height[i]){ //j尽可能取长
int s = (j - i) * height[i];
if (s > max)
max = s;
break; //h已经被限制了,而j也尽可能取长,已经是该最大值了,j前移之后会变小不用考虑了
}
else{
int s = (j - i) * height[j]; //h还有上升的可能
if (s > max)
max = s;
}
}
}
return max;
}
};
看题解

双指针移动

cpp
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int max = 0;
int left = 0,right = len - 1;
while(left != right){
int s = (right - left) * min(height[left],height[right]);
if(s > max)
max = s;
if(height[left] < height[right]){
left++;
}
else{
right--;
}
}
return max;
}
};