题目
题目来源:盛最多水的容器 - 力扣
分析
对于这个问题,首先我们要清楚这里的容积怎么算,以下图为例:
显然,这里的容积是两条红色柱子的下标差 x 矮的柱子的高度,用代码来表示就是:
const area = (right - left) * Math.min(height[left], height[right]);
结合这个,我们就可以用双指针的方式来解答本题。
tip💡:结合前面的题目可以知道,在数组中使用双指针来解决问题通常是非常有效的,这一点在 vue 2.x 的 diff 算法中也有体现。
这里我们的思路就是控制下标,不断的找下一个矮柱子即可:
var maxArea = function (height) {
let maxArea = 0;
let left = 0;
let right = height.length;
if (!height || height.length <= 1) return 0;
while (left < right) {
const area = (right - left) * Math.min(height[left], height[right]);
if (maxArea < area) {
maxArea = area;
}
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return maxArea;
};
结果如下: