Skip to content

Latest commit

 

History

History
142 lines (94 loc) · 4.21 KB

container-with-most-water.md

File metadata and controls

142 lines (94 loc) · 4.21 KB

11. Container With Most Water - 盛最多水的容器

Tags - 题目标签

Description - 题目描述

EN:

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.

 

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

 

Constraints:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

ZH-CN:

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。

 

示例 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

 

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
typescript 80 ms 50.1 MB 2022/04/12 12:19
// two pointers
function maxArea(height: number[]): number {
  let i = 0, j = height.length - 1;
  let max = 0;

  while (i < j) {
    max =  Math.max(Math.min(height[i], height[j]) * (j - i), max);

    if (height[i] < height[j] && i < j) {
      i++;
    } else if (height[i] >= height[j] && i < j) {
      j--;
    }
  }

  return max;
};

My Notes - 我的笔记

双指针法

首指针从0开始,尾指针从数组末尾开始,计算这两个指针对应的盛水面积,然后移动较短边,继续计算盛水面积,直到首尾指针相碰即可。

// two pointers
function maxArea(height: number[]): number {
  let i = 0, j = height.length - 1;
  let max = 0;

  while (i < j) {
    max =  Math.max(Math.min(height[i], height[j]) * (j - i), max);

    if (height[i] < height[j] && i < j) {
      i++;
    } else if (height[i] >= height[j] && i < j) {
      j--;
    }
  }

  return max;
};