来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water/

描述

给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。

image.png
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49

题解

暴力法

  1. class Solution {
  2. public int maxArea(int[] height) {
  3. int maxArea = 0;
  4. for (int i = 0; i < height.length; i++) {
  5. for (int j = i + 1; j < height.length; j++) {
  6. maxArea = Math.max(maxArea, Math.min(height[i], height[j]) * (j - i));
  7. }
  8. }
  9. return maxArea;
  10. }
  11. }

复杂度分析

  • 时间复杂度:11. 盛最多水的容器(Container With Most Water) - 图211. 盛最多水的容器(Container With Most Water) - 图3次轮询;
  • 空间复杂度:11. 盛最多水的容器(Container With Most Water) - 图4

    双指针法

    TIPS:将较短线段的指针向较长线段那端移动一步
    如果将较长线段的指针向内侧移动,矩形区域的面积将受限于较短的线段而不会获得任何增加。但是,在同样的条件下,移动较短线段的指针尽管造成了矩形宽度的减小,但却可能会有助于面积的增大。

    1. class Solution {
    2. public int maxArea(int[] height) {
    3. int maxArea = 0, l = 0, r = height.length - 1;
    4. while (l < r) {
    5. maxArea = Math.max(maxArea, Math.min(height[l], height[r]) * (r - l));
    6. if (height[l] < height[r]) {
    7. l++;
    8. } else {
    9. r--;
    10. }
    11. }
    12. return maxArea;
    13. }
    14. }

    复杂度分析

  • 时间复杂度:11. 盛最多水的容器(Container With Most Water) - 图5,一次扫描;

  • 空间复杂度:11. 盛最多水的容器(Container With Most Water) - 图6