Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

盛水最多的容器-11 #3

Open
sl1673495 opened this issue May 1, 2020 · 0 comments
Open

盛水最多的容器-11 #3

sl1673495 opened this issue May 1, 2020 · 0 comments
Labels
例题详解 每个分类下会挑出几道题目进行精讲,其他的同类题目会默认拥有这些前置知识而简略讲解。 双指针

Comments

@sl1673495
Copy link
Owner

给你 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
}
@sl1673495 sl1673495 added 双指针 例题详解 每个分类下会挑出几道题目进行精讲,其他的同类题目会默认拥有这些前置知识而简略讲解。 labels May 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
例题详解 每个分类下会挑出几道题目进行精讲,其他的同类题目会默认拥有这些前置知识而简略讲解。 双指针
Projects
None yet
Development

No branches or pull requests

1 participant