LeetCode每日一练 -- Container With Most Water
Brute Force
/*
* @Author: fox
* @Date: 2022-04-27 09:07:49
* @LastEditors: fox
* @LastEditTime: 2022-04-27 11:02:06
* @Description: https://leetcode.com/problems/container-with-most-water/
*/
/**
* @description: Brute Force
* 虽然成功了,但是...Time Limit Exceeded!在面对大量数据的时候,这个方法显然是不合适的,效率太低
* @param {number[]} height
* @return {number}
*/
const maxArea = (height) => {
// 1. 如果height数组的长度为0或1的时候,直接返回0
if (!height || !height.length || height.length === 1) return 0;
let area = 0; // 最大区域
// 2. 双重循环遍历,计算所有区域面积,然后取最大值
for (let x = 0; x < height.length; x++) {
for (let y = x + 1; y < height.length; y++) {
const small = height[x] < height[y] ? height[x] : height[y];
const tempArea = small * (y - x);
area = tempArea > area ? tempArea : area;
};
};
return area
};
let height;
height = [1, 8, 6, 2, 5, 4, 8, 3, 7];
console.log(maxArea(height)); // 49
height = [1, 1];
console.log(maxArea(height)); // 1
Two Pointer Approach
/*
* @Author: fox
* @Date: 2022-04-27 09:07:49
* @LastEditors: fox
* @LastEditTime: 2022-04-27 16:06:55
* @Description: https://leetcode.com/problems/container-with-most-water/
*/
/**
* @description Two Pointer Approach
* @param {number[]} height
* @return {number}
*/
const maxArea = (heights) => {
let [l, r] = [0, heights.length - 1]
let max = 0;
while (l < r) {
max = Math.max(max, (r - l) * Math.min(heights[l], heights[r]));
// 初始状态下,x轴的宽度我们已经获取了最大值,并且担任了最大区域,这个时候如果不移动较短的一条线,区域并不会再增加,并且
// 还会减少,这是因为height取决于最短的一条线。所以应该移动它,这样矩形区域在x轴的损失的面积关联可能会被高度弥补
if (heights[l] < heights[r]) {
l++;
} else {
r++;
}
}
return max;
};
let height;
height = [1, 8, 6, 2, 5, 4, 8, 3, 7];
console.log(maxArea(height)); // 49
height = [1, 1];
console.log(maxArea(height)); // 1