LeetCode 11. Container With Most Water

来源:互联网 发布:炒白银实时数据 编辑:程序博客网 时间:2024/05/28 15:51

题目:

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.

题意:

给定n个非负整数生成n条垂直X轴的线,找到2条线与X轴形成的矩形最大。


题解:

1. 暴力破解法,找出所有矩形容积,再求最大值。不过超时。时间复杂度为O(n^2)

2. 从该数组最左和最右开始找。

    如果左边值比较大,右边左移一位,

   反之,左边右移一位。

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

时间复杂度为O(n)。





0 0
原创粉丝点击