LeetCode 训练题2

1. ContainerWith Most Water

Given n non-negativeintegers a1a2, ..., an,where each represents a point at coordinate (iai). n verticallines are drawn such that the two endpoints of line i isat (iai)and (i, 0). Find two lines, whichtogether with x-axis forms a container, such that the container contains themost water.

Note: You may not slant the container and n is at least 2.


Translation:

给定n个非负整数a1a2...an,其中每个代表坐标(iai)处的一个点。绘制n条垂直线,使得线i的两个端点处于(iai)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,以使容器包含最多的水。

注意:您不得倾斜容器,并且n至少为2


这道题目可以用算法复杂度为O(n^2)的暴力解法:通过从左到右遍历将所有可能的面积进行比较,最终返回最大面积。但如果n的数量较大,则可能会超时。

所以要考虑到短板问题和减少算法复杂度——短板问题,水的容量取决于较短的那块板;

扫描二维码关注公众号,回复: 1048805 查看本文章

考虑减少算法复杂度,从左右两边往中间夹逼。算法复杂度为O(n)。

这里,假设有6条线(6块板),分别设为a1,a2,a3,a4,a5,a6;

取pos1=起始(i1),pos2=末尾(i6)

假设a1>a6,则此时面积s=a6*(pos2-pos1

若定pos2,向右移动pos1,当a(pos_new)>a(原pos1),则s_new=a6*(pos2-pos_new)<s;

当a6<a(pos_new)<a(原pos1),则s_new=a6*(pos2-pos_new)<s;

当a(pos_new)<a6<a(原pos1),则s_new=a(pos_new)*(pos2-pos_new)<s;

所以移动pos1,得到的面积都比原来小

所以算法设计为哪个板高,定住高的板,移动矮的板pos


代码:(python3)

class Solution:
    def maxArea(self, height):
        pos1=0
        pos2=len(height)-1
        area = 0
        while pos1!=pos2:
            if height[pos1]<height[pos2]:
                area_ = height[pos1]*(pos2-pos1)
                if area_>area:
                    area = area_
                pos1+=1
            else:
                area_ = height[pos2]*(pos2-pos1)
                if area_>area:
                    area = area_
                pos2-=1     
        return area



猜你喜欢

转载自blog.csdn.net/qq_798779022zzc/article/details/80319529
今日推荐