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;
    }
};
相关推荐
空白到白15 小时前
决策树-面试题
算法·决策树·机器学习
flashlight_hi15 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
前端世界15 小时前
HarmonyOS 数据处理性能优化:算法 + 异步 + 分布式实战
算法·性能优化·harmonyos
楼田莉子15 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon3415 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
陈序猿(代码自用版)15 小时前
【考研C语言编程题】数组元素批量插入实现(含图示+三部曲拆解)
c语言·开发语言·考研
kyle~15 小时前
排序---冒泡排序(Bubble Sort)
c语言·c++·算法
l1t15 小时前
我改写的二分法XML转CSV文件程序速度追上了张泽鹏先生的
xml·c语言·人工智能·算法·expat
一碗白开水一15 小时前
【论文阅读】Far3D: Expanding the Horizon for Surround-view 3D Object Detection
论文阅读·人工智能·深度学习·算法·目标检测·计算机视觉·3d
轮到我狗叫了16 小时前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode