408算法题leetcode--第25天

128. 最长连续序列

  • 128. 最长连续序列
  • 思路:如注释
  • 时间和空间:O(n)
  • unordered_set: 无序容器,只存key且不重复
cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        // 去重
        // 判断每个数是否为序列开头,如果不是就跳过,如果是就往后遍历直到序列结束
        unordered_set<int>sets;
        for(auto it : nums){
            sets.insert(it);
        }
        int ret = 0;
        for(auto it : sets){
            if(!sets.count(it - 1)){
                // 是开头,往后遍历
                int t = 1;
                while(sets.count(it + 1)){
                    it++;
                    t++;
                }
                ret = max(ret, t);
            }
        }
        return ret;
    }
};

739. 每日温度

  • 739. 每日温度
  • 时间和空间:O(n)
  • 单调栈:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了;空间换时间;用来存放之前遍历过的元素;求比自己大的元素用递增栈(从栈顶到底部);结果数组:栈顶元素弹出时,用当前下标减去栈顶元素的下标即结果
cpp 复制代码
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        stack<int>stk;  // 记录下标,因为输出下标
        vector<int>v(temperatures.size(), 0);
        stk.push(0);
        int size = temperatures.size();
        for(int i = 1; i < size; i++){
            // 出栈,输出结果
            while(!stk.empty() && temperatures[i] > temperatures[stk.top()]){
                v[stk.top()] = i - stk.top();
                stk.pop();
            }
            stk.push(i);
        }
        return v;
    }
};
相关推荐
yvestine几秒前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
GalaxyPokemon30 分钟前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime1 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
aichitang20242 小时前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵
OpenCSG2 小时前
电子行业AI赋能软件开发经典案例——某金融软件公司
人工智能·算法·金融·开源
chao_7893 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
dfsj660113 小时前
LLMs 系列科普文(14)
人工智能·深度学习·算法
薛定谔的算法4 小时前
《盗梦空间》与JavaScript中的递归
算法
kaiaaaa4 小时前
算法训练第十一天
数据结构·算法
?!7144 小时前
算法打卡第18天
c++·算法