题目描述

题解
// 双指针法
// 双指针从左右往中间移动(不用从左到右划窗)
// 容积长方形是宽×高,宽是两个指针的距离,高是两个指针中取短的那一个(木桶效应)
// 值得注意的是,为了追求最大的容积,双指针中,高度低的那个指针才继续移动。
// 执行用时:5 ms, 在所有 Java 提交中击败了39.51%的用户
// 内存消耗:52.2 MB, 在所有 Java 提交中击败了5.02%的用户
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int res = 0;
while (left < right) {
res = Math.max(res, (right - left) * Math.min(height[right], height[left]));
if (height[left] <= height[right])
left++;
else
right--;
}
return res;
}
}
// 优化一点
// 执行用时:4 ms, 在所有 Java 提交中击败了73.72%的用户
// 内存消耗:52.1 MB, 在所有 Java 提交中击败了6.03%的用户
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int res = 0;
while (left < right) {
if (height[left] <= height[right]) {
res = Math.max(res, (right - left) * height[left]);
left++;
}
else {
res = Math.max(res, (right - left) * height[right]);
right--;
}
}
return res;
}
}