我试图解决以下问题:
https://leetcode.com/problems/largest-rectangle-in-histogram/
我现在的代码总是一两个。此外,它的网站运行速度太慢(获得超出时间限制的错误)。
我的代码粘贴在下面。有人可以看到错误的位置,以及我如何改进现有的代码以使其有效?
class Solution(object):
def largestRectangleArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
dic = {}
#secondList is for storing deleted items.
secondList = []
if not height:
return 0
#stores the max rectangle strting from 'key', a height.
for index in range(len(height)):
num = height[index]
for entry in dic:
if num >= entry[0]:
dic[entry] += entry[0]
else:
#if num is less than it
secondList.append(dic[entry])
dic[(num ,entry[1])] = (index+1-entry[1])*num
del dic[entry]
dic[(num, index)] = num
if secondList:
secondList = max(secondList)
return max(max([dic[i] for i in dic]), secondList)