Skip to content

盛水最多的容器-11 #3

@sl1673495

Description

@sl1673495

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

说明:你不能倾斜容器,且  n  的值至少为 2。

image

思路

这题利用双指针去做,i 指向最左边,j 指向最右边。当发现左边比较高的时候,保持左边
不动,右边左移。当发现右边比较高的时候,保持右边不动,左边右移。在这个过程中不断
更新最大值,最后 i === j 的时候,即可求得最大值。

题解

let maxArea = function(height) {
  let i = 0
  let j = height.length - 1

  let max = 0

  while (i !== j) {
    let leftHeight = height[i]
    let rightHeight = height[j]

    let x = j - i
    let area
    if (leftHeight > rightHeight) {
      area = rightHeight * x
      j--
    } else {
      area = leftHeight * x
      i++
    }
    max = area > max ? area : max
  }

  return max
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    例题详解每个分类下会挑出几道题目进行精讲,其他的同类题目会默认拥有这些前置知识而简略讲解。双指针

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions