LeetCode 11. Container With Most Water

题目要求:

Given n non-negative integers a1, a2, ..., an, 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.


分析:
1.暴力求解:
      在每一种匹配情况下进行比较,留下最大的"乘积"
   algorithm:
     pre: a list of int -- height
     psot: the max area
    
     area <- 0
     for i <- 0 to height.size():
 for j <- i+1 to height.size() :
           h <- min(height[i], height[j])
           if (j-i)*h > area :
       area = (j-i)*h
     return area
  时间复杂度: O(N^2)
2.
  从底最大开始,当底不断减小,避免面积一定减小的情况。
 
  底的长度为   匹配个数
    size          1
    size-1        2
    size-2        3
    ...          ...
    2            size-1
 
  我们是只要求出最大面积,而不必要对所有的都进行求解,在当前情况下,只需向一定不是面积减小的方向变化即可。
简单的情况
  长度为size的时候:
    变为长度为size-1的情况,有且只有两种方式:[0,size-2]和[1,size-1]
  面积求法为: d*h ; 其中h为height[0], height[size-1]中的最小值。
    不妨设height[0]是最小值,则[0,size-2]的面积一定是变小的(这里不再解释)所以下一情况中只需查看[1,size-1]的情况。
    以height[0]为左边界的任何长度不大于size的匹配面积都小于当前area:这里的比较排除了n-2种情况。[0:1]\[0:2]\……\[0:size-2]
更为一般的情况:
  现假定计算的 范围为[i:j] 且有i<j
      当对范围进行进一步缩小时:
   if height[i] < height[j]
      i+= 1
          else
             j += 1
      排除的其它比较情况数为 j-i-1 种
 [i:i+1]\……\[i:j-1]
算法:
    i <- 0 , j <- size-1
    area <- 0
    while i < j :
 h <- min(height[i],height[j])
 if (j-i)*h > area
    area <- (j-i)*h
 
 //范围更新       
        if height[i] <= h
     i += 1
        else
     j -= 1     
代码:
def maxArea(height ):
    '''
    height : list[int]
    return type: int
    '''
    ans = 0
    
    i = 0
    j = len(height)-1
    while i < j :
        h = min( height[i] , height[j] )
        new_area = (j-i)*h
        if new_area > ans :
            ans = new_area

        if height[i] == h :
            i += 1
        if height[j] == h :
            j -= 1
    return ans 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值