LeetCode-011-盛最多水的容器
思路
双指针法,从两边向中间靠,易知,容量由短板决定,考虑两种情况:
- 短边缩进:短边可能变长, 虽然底宽减一了,但是可能容量增加
- 长边缩进:短边可能更短,底宽减一了,所以容量一定减少
综上,选择短边缩进策略。
代码
class Solution {
public int maxArea(int[] height) {
int res=0;
int i=0,j=height.length-1;
while(i!=j){
int h=Math.min(height[i],height[j]);
res=Math.max(h*(j-i),res);
if(h==height[i])i++;
else j--;
}
return res;
}
}