美文网首页
盛最多水的容器

盛最多水的容器

作者: 路过_720a | 来源:发表于2020-03-25 21:59 被阅读0次

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

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

解题思路:
1.暴力法
  遍历所有可能的矩形,返回最大值。

func maxArea(height []int) int {
    l := len(height)
    max := 0
    for i := 0; i < l-1; i++ {
        for j := i + 1; j < l; j++ {
            max = maxInt(max, minInt(height[i], height[j])*(j-i))
        }
    }

    return max
}

2.双指针法
  首先选择长最大的矩形,然后逐步缩短长。为了得到可能的最大面积,新的宽长度比原来的大才有可能,因而移动较短的宽来缩短长。

func maxArea(height []int) int {
    begin, end, max := 0, len(height) - 1, 0
    for ; begin < end; {
        left, right := height[begin], height[end]
        max = maxInt(max, minInt(left, right) * (end - begin))
        if left < right {
            begin++
        } else {
            end--
        }
    }

    return max
}

辅助函数

func minInt(a, b int) int {
    if b < a {
        return b
    }
    return a
}

func maxInt(a, b int) int {
    if a < b {
        return b
    }
    return a
}

相关文章

  • 盛最多水的容器

    给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直...

  • 盛最多水的容器

    盛最多水的容器 给定n个非负整数a1,a2,...,an,每个数代表坐标中的一个点(i,ai) 。画n条垂直线,使...

  • 盛最多水的容器

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/cont...

  • 盛最多水的容器

    题目描述 思路 题解代码

  • 盛最多水的容器

    盛最多水的容器 难度中等1826 收藏 分享 切换为英文 关注 反馈 给你 n 个非负整数 a1,a2,...,a...

  • 盛最多水的容器

    题目描述:  给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内...

  • 盛最多水的容器

    给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直...

  • 盛最多水的容器

    题目 https://leetcode-cn.com/problems/container-with-most-w...

  • 盛最多水的容器

    题目: 题目的理解: 计算两个数之间的面积,获取到最大的面积。 时间复杂度为O(n!), 当数量越大计算时间越长,...

  • 盛最多水的容器

    LeetCode第十一题 题目描述:给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i...

网友评论

      本文标题:盛最多水的容器

      本文链接:https://www.haomeiwen.com/subject/odwbyhtx.html