• leetcode_11. 盛最多水的容器


    给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
    
    说明:你不能倾斜容器。
    
     
    
    示例 1:
    
    
    
    输入:[1,8,6,2,5,4,8,3,7]
    输出:49 
    解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
    示例 2:
    
    输入:height = [1,1]
    
    
    输出:1
    示例 3:
    
    输入:height = [4,3,2,1,4]
    输出:16
    示例 4:
    
    输入:height = [1,2,1]
    输出:2
     
    
    提示:
    
    n = height.length
    2 <= n <= 3 * 104
    0 <= height[i] <= 3 * 104
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/container-with-most-water
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    #暴力解法,超时
    class Solution:
        def maxArea(self, height: List[int]) -> int:
            length=len(height)
            maxarea=0
            for i in range(length):
                for j in range(i+1,length):
                    maxarea=max(maxarea,min(height[i],height[j])*(j-i))
            return maxarea
    
    #双指针,移动值小的,暂时固定值大的,O(n)
    class Solution:
        def maxArea(self, height: List[int]) -> int:
            p1=0
            p2=len(height)-1
            max_area=0
            while(p1<p2):
                max_area=max(max_area,min(height[p1],height[p2])*(p2-p1))
                if height[p1]<height[p2]:
                    p1+=1
                else:
                    p2-=1
    
            return max_area
    
  • 相关阅读:
    c++引用(reference)
    c++ 三目运算符功能增强
    C++ “新增”bool类型关键字
    C++ struct
    C++命名空间(namespace)
    基于python 实现KNN 算法
    Chrome 快捷键使用
    WOE(weight of evidence, 证据权重)
    python 命令运行环境下 ModuleNotFoundError: No module named 'Test'
    基于python 信用卡评分系统 的数据分析
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14103252.html
Copyright © 2020-2023  润新知