9.2 练手 腾讯50题 11算水槽容量

本文详细解析了如何解决经典的容器盛水问题,通过双指针算法寻找两直线间能容纳的最大水量,给出了清晰的实现思路与代码示例。

11. 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.

 

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

思路:

在数组左右两端设立指针朝中间遍历,每个循环往左或者往右移动长度最小的指针使得当前最大面积增加,如果不增加就继续保持,一直移动到循环结束, 最后返回最大面积,代码如下:

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        if n == 2:
            return min(height)
        left = 0
        right = n - 1
        maxArea = min(height[0], height[n-1])*(n-1)
        while(right > left):
            if(height[left]<=height[right]):
                left += 1
            else:
                right -= 1
            curArea = min(height[left], height[right]) * (right-left)
            if(curArea > maxArea):
                maxArea = curArea
        return maxArea

开始的时候思路出了一点错误,以为只要找到一个最大和次大的数值的然后由内向外循环排除能够找到,问题是没有考虑可能最优区间内并不全部包含最大和次大的数值,此时应该是底下的index对Area的贡献最高。

其实双指针这个方法就是当index影响很大的时候如果把数组的x,y坐标交换,从外向内遍历的一种妥协吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值