• Container With Most Water


    Given n non-negative integers a1, a2, ..., a, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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.

    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

    Example:

    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49

    思路:
    最左与最右分别设置两个点:l,r,
    设它们的高为:hl,hr
    先记录一次面积:
    area = (r-l)*min(hl,hr)
    即为:两点间的距离*两者之间最矮的高度

    假设在l,r原始点之内仍有可能存在更大的面积组合:
    因为要往里找新的l,r组合,长度(r-l)是一直在缩小的,如果存在更大面积,则一定存在更长的高,则min(*hr,*hl)>min(hr,hl)
    假设一开始,hr > hl, area = (r-l) * hl ;如果存在更大面积, 则*hl > hr, *area = (r-*l) * hr,因hr > hl, *area有可能会大于原面积
    假设,hr < hl, area = (r-l) * hr ;如果存在更大面积, 则*hr > hl, *area = (*r-l) * hl, 因hl > hr, *area有可能会大于原面积

    如果hl == hr 怎么办?
    不断同时移动两个点,直到新的lr的高度同时大于原来的高度:
    因为r-l一直在缩小,min(hl,hr)必须变大,所以hr,hl要同时变大才,有机会超越原来的面积。

    class Solution(object):
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            l,r = 0, len(height)-1
            box = [self.getarea(height, l, r)]
            
            while l < r:
                if l < r and height[l] < height[r]:
                    l += 1
                    if l < r and height[l] > height[l-1]:
                        box.append(self.getarea(height, l, r))
                if l < r and height[l] > height[r]:
                    r -= 1
                    if l < r and height[r] > height[r+1]:
                        box.append(self.getarea(height, l, r))
                if l < r and height[l] == height[r]:
                    now = height[l]
                    while l < r and now >= height[l]:
                        l += 1
                    while l < r and now >= height[r]:
                        r -= 1
                    box.append(self.getarea(height, l, r))
            return max(box)
                    
        def getarea(self, height, l, r):
            return (r-l)*min(height[l], height[r])


  • 相关阅读:
    使用RecyclerView打造Gallery
    Retrofit简介与使用方法(翻译)
    迷宫实现递归版本C++
    牛客笔试题
    牛客笔试题---求最长重复词长度之和
    C++句柄解析
    C++双向循环链表实现
    String C++完整实现。
    String写时拷贝实现
    顺序表操作补充(查找方法增加)
  • 原文地址:https://www.cnblogs.com/phinza/p/11403385.html
Copyright © 2020-2023  润新知