双指针:盛最多水的容器(给定高度数组,选两条线使面积最大)。
思路:左右指针夹逼。面积 = 短边 × 距离。每次移动较短的那一端(移动长边不可能增大面积)。
function maxArea(height) {
let left = 0, right = height.length - 1, max = 0
while (left < right) {
const h = Math.min(height[left], height[right])
max = Math.max(max, h * (right - left))
if (height[left] < height[right]) left++
else right--
}
return max
}- 时间
O(n),空间O(1) - 经典贪心 + 双指针:证明「移动短板才可能变优」是关键