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


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

    思路:矩形面积最大,比较简单

    方案一:两个循环,很容易实现,耗时有点长

    class Solution:
        def maxArea(self, height: List[int]) -> int:
            max_area = 0
            temp_area = 0
            length = 0
            max_length = len(height)
            if max_length < 2:
                return 0
            for i in range(max_length):
                for j in range(max_length):
                    if height[i] <= height[j] :
                        short_height = height[i]
                        high_height = height[j]
                        length = abs(j - i)
                        temp_area = short_height * length
                    else:
                        short_height = height[j]
                        high_height = height[i]
                        length = abs(i - j)
                        temp_area = short_height * length
                    if temp_area >= max_area:
                        temp = temp_area
                        temp_area = max_area
                        max_area = temp
            return max_area
    方案二:
    class Solution:
        def maxArea(self, height: List[int]) -> int:
            max_area = 0
            temp_area = 0
            index1 = 0
            index2 = len(height) - 1
            while index1 < index2:
                if height[index1] <= height[index2]:
                    short_height = height[index1]
                    high_height = height[index2]
                    length = index2 - index1
                    temp_area = short_height * length
                    index1 += 1
                else:
                    short_height = height[index2]
                    high_height = height[index1]
                    length = index2 - index1
                    temp_area = short_height * length
                    index2 -= 1
                if temp_area >= max_area:
                    temp = temp_area
                    temp_area = max_area
                    max_area = temp
            return max_area 
  • 相关阅读:
    【转载】10个Web3D可视化精彩案例
    基于react的audio组件
    如何开发一款堪比APP的微信小程序(腾讯内部团队分享)
    CSS3 用border写 空心三角箭头 (两种写法)
    浅谈微信小程序对于创业者,意味着什么?
    左手Cookie“小甜饼”,右手Web Storage
    css3中user-select的用法详解
    个人感觉一些比较有用的特效例子
    纯css模拟电子钟
    蓝桥杯 ALGO-2:最大最小公倍数
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12719868.html
Copyright © 2020-2023  润新知