[Leetcode] 11. Container With Most Water

Problem

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.

思路:
这里相当于求最大矩形面积。这里有一个tradeoff,一个是横轴的长度(距离),一个是纵轴的高度。
1. 暴力地做两层循环,遍历其中两两元素,求最大的矩形面积,时间复杂度为O(n^2)。这种暴力的方法当然是TLE的……
2. 动态规划。先对高度进行从小到大排序,然后从高度最小的元素开始访问。计算离其最远的X轴距离,得到矩形面积。此后便不再考虑这个元素(短板)。这样的方法时间复杂度是O(nlogn)(排序)+O(n)(访问各个元素)。
3. 【ref】双指针法。分别分配两个指针在最左和最右,计算矩形面积。如果height[left]

def calArea(i,j,height):
    height = min(height[i],height[j])
    area = (j-i)*height
    return area

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        hlen = len(height)
        i = 0
        maxarea = 0;
        while i < hlen:
            j = i + 1
            while j < hlen:
                tmparea = calArea(i,j,height)
                maxarea = maxarea if maxarea > tmparea else tmparea
                j = j + 1
            i = i + 1
        return maxarea

Solution 2: [Accepted] 4%

class Solution(object):
    def maxArea(self, height):
        """
        #:type height: List[int]
        #:rtype: int
        """
        hlen = len(height)
        l = zip(xrange(0,hlen),height)

        newdic =  sorted(l,key = lambda d:d[1],reverse=False)
        i = 0
        maxarea = 0
        xmax = hlen - 1
        xmin = 0
        flag =  [ True for n in xrange(hlen)]
        while i < hlen-1:
            while flag[xmax] == False:
                xmax = xmax - 1
            while flag[xmin] == False:
                xmin = xmin + 1
            x1 = xmax-newdic[i][0]
            x2 = newdic[i][0]-xmin
            delta = x1 if x1 > x2 else x2
            tmparea = delta * newdic[i][1]
            maxarea = maxarea if maxarea > tmparea else  tmparea
            flag[newdic[i][0]] = False
            i = i + 1
        return maxarea

ref:
python内置方法的时间复杂度

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值