对于这题,首先明确的是:盛水的体积取决于两垂线间的距离与两垂线中最短的长度。
那么使用双指针,在每次移动时,只移动其中最短的那个,因为若移动最长的那个,体积不会变大。
class Solution {
public:
int maxArea(vector<int>& height) {
int max_v = 0;
int l = 0, r = height.size()-1;
while(l!=r){
max_v = max(max_v, (r-l)*min(height[l], height[r]));
if(height[l]<height[r]){
l++;
}else{
r--;
}
}
return max_v;
}
};
class Solution {
public int maxArea(int[] height) {
int max_v = 0;
int l = 0, r = height.length-1;
while(l!=r){
max_v = Math.max(max_v, (r-l)*Math.min(height[l], height[r]));
if(height[l]<height[r]){
l++;
}else{
r--;
}
}
return max_v;
}
}