单调栈:维持一个单调的栈,用于解决离最近的比自己大or小的元素的距离
和之前那个top k 最小堆感觉思路是一样的
python
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ans=[0]*len(temperatures)
stack=[0]
for i in range(1,len(temperatures)):
if temperatures[i]<=temperatures[stack[-1]]:
stack.append(i)
else:
while stack and temperatures[i]>temperatures[stack[-1]]:
ans[stack[-1]]=i-stack[-1]
stack.pop()
stack.append(i)
return ans
和上一题思路一样,实现上稍微绕了一下
python
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res=[-1]*len(nums1)
stack=[0]
for i in range(1,len(nums2)):
if nums2[i]<=nums2[stack[-1]]:
stack.append(i)
else:
while stack and nums2[i]>nums2[stack[-1]]:
if nums2[stack[-1]] in nums1:
idx=nums1.index(nums2[stack[-1]])
res[idx]=nums2[i]
stack.pop()
stack.append(i)
return res