leetcode | python | 盛最多水的容器

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

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

leetcode | python | 盛最多水的容器

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

 

示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 4

第一遍:

哭了,我为什么这么喜欢重复遍历,连暴力解法都做不到

class Solution:
    
    def maxArea(self, height: List[int]) -> int:
        length = len(height)
        max_area = 0
        for i in range(0,length):
            cur = height[i]
            area1 = 0
            for j in range(0, i):
                temp = min(height[j], cur) * (i - j)
                area1 = max(area1, temp)
            
            area2 = 0
            for j in range(i+1, length):
                temp = min(height[j], cur) * (j - i)
                area2 = max(area2, temp)
            
            max_area = max(max_area, area1, area2)
        return max_area

leetcode | python | 盛最多水的容器

第二遍:

暴力解法,依次遍历

class Solution:
    
    def maxArea(self, height: List[int]) -> int:
        length = len(height)
        area2 = 0
        for i,cur in enumerate(height):
            for j in range(i+1, length):
                temp = min(height[j], cur) * (j - i)
                area2 = max(area2, temp)
            
        return area2

为啥还是超出时间限制???不懂了,难道python就是慢吗

第三遍:双指针法

基本的表达式: area = min(height[i], height[j]) * (j - i) 使用两个指针,值小的指针向内移动,这样就减小了搜索空间 因为面积取决于指针的距离与值小的值乘积,如果值大的值向内移动,距离一定减小,而求面积的另外一个乘数一定小于等于值小的值,因此面积一定减小,而我们要求最大的面积,因此值大的指针不动,而值小的指针向内移动遍历

class Solution:
    def maxArea(self, height: List[int]) -> int:
        i = 0;
        j = len(height)-1
        area = 0;
        while(i<j):
            area1 = (j-i)*min(height[i],height[j])
            area = max(area,area1)
            
            if height[i]<height[j]:
                i+=1
            else: 
                j-=1
        return area

执行用时 : 92 ms, 在Container With Most Water的Python3提交中击败了47.22% 的用户

内存消耗 : 14.6 MB, 在Container With Most Water的Python3提交中击败了0.78% 的用户