算法w4——Container With Most Water

题目:leetcode 11. Container With Most Water
链接:https://leetcode.com/problems/container-with-most-water/#/description
原题:
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.
Subscribe to see which companies asked this question.
这里写图片描述
题意:
给出n个非负整数,他们代表n条直线:(i,ai)坐标与(i,0)之间的连线,找出两条直线,让他们与x轴构成一个容器,要求容器能容纳最多的水。即计算面积的时候要用最短的那条直线作为高,宽就是两条直线之间的距离。

解题思路:
首先题目含义明显,首先尝试最暴力的解决方法,将n条直线两两之间的可能性都找出来计算,然后返回最大面积。结果超时,想想也知道,题意这么简单的题目怎么可能用这么粗暴的方法,这种方法复杂度O(n^2)。
那如果要优化的话,很明显复杂度肯定比n^2小,由于输入只有一个n位长度的list,能想到最优复杂度的应该就是O(n)了。
但O(n)如何实现,这里有两种方法:
1.先看逻辑最容易理解的,我们初始化假设最大的两条直线是所有直线里面最中间的两条,也就是list里面中间的两个数。计算一下它们围成的面积,把它当成当前最大面积。然后看一下两条曲线哪条比较短一点,那我们就舍弃那条并用它隔壁的直线来代替,再计算一次面积跟当前最大面积比较。这个逻辑非常简单,因为要找最大面积,我肯定把长的直线留下来。就这样从中间两条直线往两边推开,答案肯定会在遍历过程中找到,而且复杂度只是O(n),因为每个直线只遍历了一次。
2.第二个思路跟第一个其实一个道理,只是反过来想,我把初始设置为最边上的两条直线,然后同样判断哪条短就舍弃哪条,不断往中间收紧,最终也能得出答案。

代码如下:

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        i = 0
        j = len(height)-1
        while(i < j):
            if height[i] < height[j]:
                area = height[i] * (j - i)
                if area > max_area:
                    max_area = area
                i += 1
            else:
                area = height[j] * (j - i)
                if area > max_area:
                    max_area = area
                j -= 1
        return max_area
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值