739. 每日温度
代码随想录:739. 每日温度
Leetcode:739. 每日温度
做题
暴力求解:超时
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res = []
for i in range(len(temperatures)):
flag = False
higher = 0
for j in range(i+1, len(temperatures)):
if temperatures[j] > temperatures[i]:
flag = True
res.append(j-i)
break
if not flag:
res.append(0)
return res
时间复杂度: O(n^2)
空间复杂度: O(n)
看文章
用一个单调栈记录还未找到更高温度的点。
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res = [0] * len(temperatures)
stack = []
for i in range(len(temperatures)):
while stack and temperatures[i] > temperatures[stack[-1]]:
res[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return res
时间复杂度: O(n)
空间复杂度: O(n)
496.下一个更大元素 I
代码随想录:496.下一个更大元素 I
Leetcode:496.下一个更大元素 I
做题
无简化思路。
看文章
注意题目中说是两个没有重复元素 的数组 nums1 和 nums2。没有重复元素,我们就可以用map来做映射了。根据数值快速找到下标,还可以判断nums2[i]是否在nums1中出现过。
实际上还是在nums2做单调栈,只是多加了一步:判断nums1中是否存在该元素。
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
# 创建答案数组
ans = [-1] * len(nums1)
for i in range(len(nums2)):
while len(stack) > 0 and nums2[i] > nums2[stack[-1]]:
# 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常
if nums2[stack[-1]] in nums1:
# 锁定 num1 检索的 index
index = nums1.index(nums2[stack[-1]])
# 更新答案数组
ans[index] = nums2[i]
# 弹出小元素
# 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了
stack.pop()
stack.append(i)
return ans
时间复杂度: O(n)
空间复杂度: O(n)
以往忽略的知识点小结
- 单调栈使用场景:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置。时间复杂度为O(n)。
个人体会
完成时间:1h30min。
心得:新题型单调栈,思路不难,但也需要体会感悟。