【Leetcode】011. 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.

例子

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

2016-06-03
暴力求解
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        area = 0
        for i in range(len(height)):
            for  j in range(i+1,len(height)):
                tmp = min(height[j],height[i])*(j-i)
                area = max(area,tmp)
        return area

S = Solution()
height = [1,8,6,2,5,4,8,3,7]
S.maxArea(height)

效率分析

利用python这种暴力求解的解法没有通过。
Status: Time Limit Exceeded

有没有其他办法???
在刚才的过程中,如果起始点固定为A,我们期望如果后面出现的数小于A,那么我们希望它尽可能的的靠近A。如果后面出现的数大于A,那么则希望它尽可能的远。这样分析,刚才的计算过程中就有两种情况的计算是无意义的:

  1. 定点为A,后面的小于A,越靠近的计算越不必要。
  2. 顶点为A,后面有大于A的,越靠近的计算也是无意义的。
双指针
        left,right = 0,len(height)-1
        area = 0
        while(left<right):
            tmp = min(height[left],height[right])*(right-left)
            area = max(area,tmp)
            if height[left]>=height[right]:
                right = right -1
            else : left = left +1
        # print(area)
        return area
效率分析

Runtime: 108 ms, faster than 54.84% of Python online submissions for Container With Most Water.
Memory Usage: 13 MB, less than 72.65% of Python online submissions for Container With Most Water.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值