zoukankan      html  css  js  c++  java
  • Container With Most Water

    Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

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

    分析:

    方法一:使用最简单的嵌套循环遍历,找出每一种组合。但此方法超时

    方法二:容器的盛水量取决于两块板中的最短板,所以两个指针,一头一尾,记录其盛水量,然后向中间移动其较短的板,期间记录最大盛水量,直至两个指针相遇。这样时间复杂度就由方法一的O(N2)变为了O(N)。使用两个指针,一头一尾的方法很值得借鉴。

    class Solution(object):
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            n = len(height)
            i = 0
            j = n-1
            max_area = 0
            while(i<j):
                if height[i] < height[j]:
                    area = (j-i)*height[i]
                    i += 1
                else:
                    area = (j-i)*height[j]
                    j -= 1
                if area > max_area:
                    max_area = area
            return max_area
  • 相关阅读:
    Basic knowledge of html (keep for myself)
    科学技术法转成BigDemcial
    SimpleDateFormat
    log4j 配置实例
    R 实例1
    yield curve
    if-else的优化举例
    十二、高级事件处理
    十一、Swing
    十、输入/输出
  • 原文地址:https://www.cnblogs.com/Peyton-Li/p/7736463.html
Copyright © 2011-2022 走看看