代码随想录第48天

739. 每日温度

python 复制代码
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        ans = [0] * n
        st = []
        for i in range(n - 1, -1, -1):
            t = temperatures[i]
            while st and t >= temperatures[st[-1]]:
                st.pop()
            if st:
                ans[i] = st[-1] - i
            st.append(i)
        return ans

496.下一个更大元素 I

python 复制代码
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        idx = {x: i for i, x in enumerate(nums1)}
        ans = [-1] * len(nums1)
        st = []
        for x in reversed(nums2):
            while st and x >= st[-1]:
                # 由于 x 的出现,栈顶元素永远不会是左边元素的「下一个更大元素」
                st.pop()
            if st and x in idx:  # x 在 nums1 中
                ans[idx[x]] = st[-1]  # 记录答案
            st.append(x)
        return ans

503.下一个更大元素II

python 复制代码
class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [-1] * n
        st = []
        for i in range(n * 2 - 1, -1, -1):
            x = nums[i % n]
            while st and x >= st[-1]:
                # 由于 x 的出现,栈顶元素永远不会是左边元素的「下一个更大元素」
                st.pop()
            if st and i < n:
                ans[i] = st[-1]
            st.append(x)
        return ans
相关推荐
码上淘金4 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo4 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552874 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子4 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174295 小时前
Python Day23 学习
python·学习
Ai尚研修-贾莲6 小时前
Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
python·信息可视化·数据分析·地球科学
qq_508576096 小时前
if __name__ == ‘__main__‘
python
学地理的小胖砸6 小时前
【Python 基础语法】
开发语言·python
程序员小远6 小时前
自动化测试与功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
_Itachi__7 小时前
Model.eval() 与 torch.no_grad() PyTorch 中的区别与应用
人工智能·pytorch·python