leetcode 11 Container With Most Water 盛最多水的容器
描述
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
/**
* 接雨水
* 思路是:双指针,只移动短板
* 因为移动长板,面积只会变得更小:
* 当遇到更短的板子,面积变小
* 当遇到更长的板子,面积仍然变小(因为容器面积取决于短板,长板变长没有用)
* 当遇到长度不变的板子,面积还是变小,因为每次移动之后长-1
* 因此,移动短板有可能使得面积变大或变小。 所以选择改变短板,才有可能使面积变大
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
if (height.length < 3) return getArea(0, 1, height)
let maxArea = 0
let left = 0, right = height.length - 1
while (left < right) {
maxArea = height[left] < height[right] ? Math.max(getArea(left--, right, height), maxArea) : Math.max(getArea(left, right--, height), maxArea)
}
return maxArea
};
const getArea = (left, right, arr) => (right - left) * Math.min(arr[left], arr[right])
分类:
软件工程相关 / 数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!