11.盛一共水的容器(javascript)11.ContainerWithMostWater
原创给定长度 n 整数数组 height 。有 n 垂直线,编号。 i 直线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中两行,使它们相互关联 x 轴一起构成了一个可以容纳最多水的容器。
返回容器可以存储的最大水量。
注意:您不能倾斜容器。
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.
示例 1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
说明:图中的垂直线表示输入数组。 [1,8,6,2,5,4,8,3,7]在这种情况下,容器能够容纳水的最大值(表示为蓝色部分)为 49。
示例 2:
输入:height = [1,1]
输出:1
参考解决问题的思路: 官方解题
双指针,Math.min(height[l], height[r]) * (r - l)计算体积公式
max 用于保存最大值
var maxArea = function (height) {
let max = 0
let l = 0, r = height.length - 1
while (l < r) {
let res = Math.min(height[l], height[r]) * (r - l)
max = Math.max(max, res)
if (height[l] > height[r]) {
r--
} else {
l++
}
}
return max
};
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
//代码优化,减少一些变量的使用可以提高性能。
let max = 0
let l = 0, r = height.length - 1
while (l < r) {
max = Math.max(max, Math.min(height[l], height[r]) * (r - l))
height[l] > height[r] ? r-- : l++
}
return max
};
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除