classSolution(object): defnextGreaterElement(self, findNums, nums): dic = {} stack = [] for num in nums: while stack and num > stack[-1]: dic[stack.pop()] = num stack.append(num)
res = [] for num in findNums: if num notin dic: res.append(-1) else: res.append(dic[num]) return res
classSolution(object): defnextGreaterElements(self, nums): n = len(nums) res = [-1] * n stack = [] for i in range(n): while stack and nums[stack[-1]] < nums[i]: res[stack.pop()] = nums[i] stack.append(i)
for i in range(n): while stack and nums[stack[-1]] < nums[i]: res[stack.pop()] = nums[i] return res
for each index i, walk right to find the left border and right border. Time = O($n^2$)
Solution2. Stack
Use a Stack to store all the indices of the columns that form an ascending order stack that stores the indeices in ascending order. [1, 5, 6
When scanning the element with index = 4, M[4] = 2 < M[3] = 6, so we keep checking left column of index 4, and calculate the area of index 3,2 and pop them out of the stack, after this step, the stack is [1, 5
Priciple, to maintain the stack to make sure the colums shose indices are stored in the stack from an sacending order.
TimeO(n), because every single element can only be inserted and popped out of the stack once and only once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): deflargestRectangleArea(self, heights): stack = [] hs = heights + [0] i = 0 res = 0 while i <= len(hs)-1: ifnot stack or hs[stack[-1]] < hs[i]: stack.append(i) i += 1 else: idx = stack.pop() res = max(res, hs[idx] * (i ifnot stack else (i-stack[-1]-1)) ) return res
classSolution(object): deftrap(self, height): n = len(height) stack = [] res = 0 i = 0 while i <= n-1: ifnot stack or height[i] <= height[stack[-1]]: stack.append(i) i += 1 else: t = stack.pop() ifnot stack: continue res += (min(height[stack[-1]], height[i]) - height[t]) * (i - stack[-1] - 1) return res