维持一个单调递增的栈,向栈逐一pushtemperatures
里的index。
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = [0]
answer = [0] * len(temperatures)
for i in range(1, len(temperatures)):
if temperatures[i] <= temperatures[stack[-1]]:
stack.append(i)
else:
while len(stack) != 0 and temperatures[i] > temperatures[stack[-1]]:
answer[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return answer
O(n)
O(n)
这道题和上一题类似。
维护一个nums2的单调递增栈,只不过在pop的时候需要在nums1中寻找相应的index,这一步可以用.index(),也可以使用哈希表。
.index()
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = [-1] * len(nums1)
stack = [0]
for i in range(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:
index = nums1.index(nums2[stack[-1]])
res[index] = nums2[i]
stack.pop()
stack.append(i)
return res
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = [-1] * len(nums1)
stack = [0]
dic = {}
for i, v in enumerate(nums1):
dic[v] = i
for i in range(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:
index = dic[nums2[stack[-1]]]
res[index] = nums2[i]
stack.pop()
stack.append(i)
return res