【Leetcode】11. 盛最多水的容器

75 阅读1分钟

题目描述

在这里插入图片描述

// 11. 盛最多水的容器

// 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
// 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找
// 出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

// 说明:你不能倾斜容器。

题解

// 双指针法
// 双指针从左右往中间移动(不用从左到右划窗)
// 容积长方形是宽×高,宽是两个指针的距离,高是两个指针中取短的那一个(木桶效应)
// 值得注意的是,为了追求最大的容积,双指针中,高度低的那个指针才继续移动。
// 执行用时: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;
    }
}