LeetCode题目链接
https://leetcode.cn/problems/daily-temperatures/description/
https://leetcode.cn/problems/next-greater-element-i/
https://leetcode.cn/problems/next-greater-element-ii/description/
题解
扫盲
通过739.每日温度扫盲。用暴力写法超出时间限制。看了一遍题解写过了。好开心。
496.下一个更大元素I
设定一个单调栈,单调栈里存nums1还是nums2的数字。直接存nums2的数字再根据nums1来查。没超时,过了,但是看看更简洁的写法是什么。看题解,学了一些语法。
503.下一个更大元素II
遍历数组两次,一次求全部,一次求最后一个数的下一个更大数。不对,不止最后一个数,碰到[5, 4, 3, 2, 1]就不行了。循环遍历和终止循环遍历不知道怎么操作。看了题解,deepseek的说法是对的,遍历两遍数组。但是在这部分代码里要处理下标,还要限制只在第一遍循环入栈。
代码
#739.每日温度
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
answer = [0] * n
st = []
for i in range(n):
while len(st) != 0 and temperatures[st[-1]] < temperatures[i]:
index = st[-1]
answer[index] = i - index
st.pop()
st.append(i)
return answer
#496.下一个更大元素I
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
n1, n2 = len(nums1), len(nums2)
st = []
result = [-1] * n2
for i in range(n2):
while len(st) != 0 and nums2[st[-1]] < nums2[i]:
index = st[-1]
result[index] = nums2[i]
st.pop()
st.append(i)
ans = []
for i in range(n1):
index = nums2.index(nums1[i])
ans.append(result[index])
return ans
#503.下一个更大元素II

380

被折叠的 条评论
为什么被折叠?



