zoukankan      html  css  js  c++  java
  • LeetCode 11. [👁] Container With Most Water & two pointers

    盛最多水的容器

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

    看起来遍历求面积就可以了

    first submission
    class Solution:
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            # max area
            maxA=0
            
            for k,h in enumerate(height):
                for k2,h2 in enumerate(height):
                    if k==k2: 
                        continue
                    
                    width=abs(k2-k)
                    lowHeight=h if h2>=h else h2
                    area=width*lowHeight
                    
                    if maxA<area:
                        maxA=area
    
            return maxA
    

    Time Limit Exceeded:

    Last executed input:
    [28,342,418,...,869,766,452]
    

    spend time : 6-7.2642898

    用了六七秒这么久,一定是我太蠢了。试了一阵还是得俩for遍历才能算出所有面积比对。那就想办法优化一下O(n^2)。看起来好像没法优化了。
    要不从中间截一下,取平均值,对。
    还是超时的,再卡卡这个范围。找找其他解法,
    目标,缩短到500ms

    发现related topics有双指针标签Two Pointers,去搜索了解下,太机智了。看了解答也是用双指针。

    解法就是固定宽度,然后去找较高的,这样O(n)就解决了。

    second submission
     class Solution:
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            # max area
            maxA=0
            l=len(height)
    
            i=0
            j=len(height)-1
            
            while i<=j and j<l:
                lowHeight=height[i] if height[i]<=height[j] else height[j]
    
                area=lowHeight*(j-i)
                if area>maxA:
                    maxA=area
    
                if height[i]>height[j]:
                    j-=1
                else:
                    i+=1
                #print(i,j)
    
            return maxAa
    

    spend time: 0.00233s
    AC! (以后看了解答的,就在名字前放个眼睛。)

    总结一下双指针:

    两个游标,头尾各一个,偏向满足的条件则不动,另一个朝对方移动,直到相遇

    双指针活活的把O(n^2)问题变成了O(n),从6~7s缩短到2ms要是我肯定想一个月都想不到,到自己的思维怪圈就出不来了。不能靠蛮力取胜,要加强自己的基础。

    扩展阅读

  • 相关阅读:
    [Java] JDBC 06 批Transaction处理 -- conn.setAutoCommit(false); // 不让其自动提交 (很重要的知识点)
    [Java] JDBC 05 TestBatch.java 批处理 Batch
    [Java] JDBC 04 TestProc.java (对存储过程进行调用 CallableStatement)
    [Java] JDBC 03 TestPrepStmt.java
    美化复选框
    美化单选框
    canvas
    html5新增标签
    旋转、水平翻转、垂直翻转
    dede让channelartlist标签支持currentstyle属性 完美解决
  • 原文地址:https://www.cnblogs.com/warcraft/p/9373189.html
Copyright © 2011-2022 走看看