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;
    }
};
相关推荐
淡海水11 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
leobertlan11 小时前
好玩系列:训练一个神经网络模型指导小孩玩游戏2-大局观教练
算法
Tisfy12 小时前
LeetCode 3876.构造奇偶一致的数组 II:三种情况分类讨论(其实还是脑筋急转弯)
算法·leetcode·题解·脑筋急转弯
乐迪信息13 小时前
智慧港口船舶AI算法实现在线状态监测
大数据·人工智能·深度学习·算法·计算机视觉
木井巳14 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊15 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥15 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
shehuiyuelaiyuehao15 小时前
算法34,位运算符操作,总结
算法
Navigator_Z15 小时前
LeetCode //C - 1224. Maximum Equal Frequency
c语言·算法·leetcode
Navigator_Z16 小时前
LeetCode //C++ - 1226. The Dining Philosophers
c语言·算法·leetcode