Problem
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.
思路:
这里相当于求最大矩形面积。这里有一个tradeoff,一个是横轴的长度(距离),一个是纵轴的高度。
1. 暴力地做两层循环,遍历其中两两元素,求最大的矩形面积,时间复杂度为O(n^2)。这种暴力的方法当然是TLE的……
2. 动态规划。先对高度进行从小到大排序,然后从高度最小的元素开始访问。计算离其最远的X轴距离,得到矩形面积。此后便不再考虑这个元素(短板)。这样的方法时间复杂度是O(nlogn)(排序)+O(n)(访问各个元素)。
3. 【ref】双指针法。分别分配两个指针在最左和最右,计算矩形面积。如果height[left]
def calArea(i,j,height):
height = min(height[i],height[j])
area = (j-i)*height
return area
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
hlen = len(height)
i = 0
maxarea = 0;
while i < hlen:
j = i + 1
while j < hlen:
tmparea = calArea(i,j,height)
maxarea = maxarea if maxarea > tmparea else tmparea
j = j + 1
i = i + 1
return maxarea
Solution 2: [Accepted] 4%
class Solution(object):
def maxArea(self, height):
"""
#:type height: List[int]
#:rtype: int
"""
hlen = len(height)
l = zip(xrange(0,hlen),height)
newdic = sorted(l,key = lambda d:d[1],reverse=False)
i = 0
maxarea = 0
xmax = hlen - 1
xmin = 0
flag = [ True for n in xrange(hlen)]
while i < hlen-1:
while flag[xmax] == False:
xmax = xmax - 1
while flag[xmin] == False:
xmin = xmin + 1
x1 = xmax-newdic[i][0]
x2 = newdic[i][0]-xmin
delta = x1 if x1 > x2 else x2
tmparea = delta * newdic[i][1]
maxarea = maxarea if maxarea > tmparea else tmparea
flag[newdic[i][0]] = False
i = i + 1
return maxarea
ref:
python内置方法的时间复杂度