题解 | #单调栈#
单调栈
http://www.nowcoder.com/practice/ae25fb47d34144a08a0f8ff67e8e7fb5
只需一次遍历:
class Solution:
def foundMonotoneStack(self , nums: List[int]) -> List[List[int]]:
stack = []
ans = [[-1, -1] for _ in range(len(nums))]
for i in range(len(nums)):
while stack and nums[stack[-1]] > nums[i]:
ans[stack[-1]][1] = i
stack.pop()
if stack:
if nums[stack[-1]] < nums[i]:
ans[i][0] = stack[-1]
elif nums[stack[-1]] == nums[i]:
ans[i][0] = ans[stack[-1]][0]
stack.append(i)
return ans