【代码随想录】day58

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • [一、739. 每日温度](#一、739. 每日温度)
  • [二、496.下一个更大元素 I](#二、496.下一个更大元素 I)

一、739. 每日温度

暴力解超时了

cpp 复制代码
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> res(n, 0);
        for (int i = 0; i < n; i ++) {
            for (int j = i + 1; j < n; j ++) {
                if (temperatures[j] > temperatures[i]) {
                    res[i] = j - i;
                    break;
                }
            }
        }
        return res;      
    }
};

单调栈:适合求当前元素,左面或者右面第一个比当前元素大或者小的元素

cpp 复制代码
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> res(n, 0);
        stack<int> st;
        st.push(0);
        for (int i = 1; i < n; i ++) {
            while (!st.empty() && temperatures[i] > temperatures[st.top()]) {
                res[st.top()] = i - st.top();
                st.pop();
            }
            st.push(i);
        }
        return res;
    }
};

二、496.下一个更大元素 I

暴力搜索:

cpp 复制代码
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res(nums1.size(), -1);
        for (int i = 0; i < nums1.size(); i ++) {
            int tmp = -1;
            for (int j = nums2.size() - 1; j >= 0; j --) {
                if (nums2[j] > nums1[i]) {
                    res[i] = nums2[j];
                }
                if (nums2[j] == nums1[i]) {
                    break;
                }
            }
        }
        return res;
    }
};

单调栈:

cpp 复制代码
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        stack<int> st;
        vector<int> res(nums1.size(), -1);
        unordered_map<int, int> umap;
        for (int i = 0; i < nums1.size(); i ++) {
            umap[nums1[i]] = i;
        }
        st.push(0);
        for (int i = 1; i < nums2.size(); i ++) {
            while (!st.empty() && nums2[i] > nums2[st.top()]) {
                int num = nums2[st.top()];
                if (umap.count(num) > 0) {
                    res[umap[num]] = nums2[i];
                }
                st.pop();
            }
            st.push(i);
        }
        return res;
    }
};
相关推荐
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼4 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
m0_547486664 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark4 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her14 天前
并查集-听课笔记
笔记·算法·并查集
码流子4 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark4 天前
从算法设计模式看编程思维的抽象能力4
算法