描述:
实现1 -- 求所有可能的值,O(N^2),超时了(因为超时没有跑所有的测试用例,所以不确定还有没有其他问题)
代码:
def maxArea(self, height):
tmp = len(height)
if tmp == 0 or tmp == 1: return 0
if tmp == 2: return abs(height[1] - height[0]) minus_lst = [height[i] - height[i-1] for i in range(1, len(height))]
# len(minus_lst) >= 2 dis, max, l = 2, 0, len(minus_lst) while True:
for i in range(l):
if i + dis > l: break area = abs(sum(minus_lst[i:i+dis]) * dis)
if area > max: max = area dis += 1
if dis > l: break return max
实现2:
对于每一个节点,取比他长的节点的位置,此时area = 距离差 * 这个节点的高度,实践复杂度 O(N^2),超时
代码:
def maxArea(self, height):
tmp = len(height)
result = 0 for i in range(tmp):
for j in range(tmp):
if height[j] >= height[i]:
area = height[i] * abs(i - j)
if area > result: result = area return result
优化-1 依然超时
def maxArea(self, height):
tmp = len(height)
result = 0 record = []
for i in range(tmp):
for j in range(tmp):
if height[j] >= height[i]:
record.append(abs(j - i))
area = height[i] * max(record)
if area > result: result = area
record = [] return result
优化-2 超时
def maxArea(self, height):
tmp = len(height)
result = 0 for i in range(tmp):
t = None
for j in range(i):
if height[j] > height[i]:
t = abs(j - i)
break if t is not None:
area_1 = t * height[i]
if area_1 > result: result = area_1 t = None
for j in range(i, tmp)[::-1]:
if height[j] > height[i]:
t = abs(j - i)
break if t is not None:
area_2 = t * height[i]
if area_2 > result: result = area_2 return result
实现3
从左端点和右端点开始,贪婪,不断取小的值推进,符合直觉,如何证明可以使用贪婪
当左边是i右边是j时,ij之间不会有更大的,两边?
todo