码迷,mamicode.com
首页 > 其他好文 > 详细

11. Container With Most Water

时间:2016-02-18 21:16:45      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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.

O(n2)方法:

class Solution(object):
    def maxArea_stupid(self, height):
        max_area = 0
        for i, vi in enumerate(height):
            for j, vj in enumerate(height):
                area = abs(i - j) * min(vi, vj)
                max_area = max(area, max_area)
        return max_area

此方法直接Time Limit Exceeded没有通过。

O(n)方法:

class Solution(object):
    def maxArea(self, height):
        max_area = 0; i = 0; j = len(height) - 1
        while i < j:
            max_area = max(max_area, (j - i) * min(height[i], height[j]))
            if height[i] < height[j]:
                i += 1
            else:
                j -= 1
        return max_area

此方法AC。

思路:

①: 假设i,j为当前最大面积对应的坐标,那么i左边一定不会有比i更高的线,否则违背了最大面积的假设;同理j也是。

②: 所以取得更大面积的坐标一定在[i, j]的内部,从两头往中间靠拢,优先收缩小的。

11. Container With Most Water

标签:

原文地址:http://www.cnblogs.com/zhuifengjingling/p/5199151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!