力扣128. 最长连续序列(哈希表)

Problem: 128. 最长连续序列

文章目录

题目描述

思路

1.先将数组中的元素存入到一个set集合中(去除重复的元素)

2.欲找出最长连续序列(先定义两个int变量longestSequence和currentSequence用于记录最长连续序列和当前最长序列),我们可以在遍历给定数组时(当前遍历到的元素为numsi)去set集合中查找numsi - 1,是否存在;若存在,直接遍历下一个nums中的元素;若不存在则持续查找numsi + 1,是否存在于set集合中,若存在则更新currentSequence和longestSequence

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为数组nums的长度

空间复杂度:

O ( n ) O(n) O(n)

Code

cpp 复制代码
class Solution {
public:
    /**
     * Hash
     * 
     * @param nums Given array
     * @return int
     */
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> set;
        // Save data to set to achieve deduplication
        for (int i = 0; i < nums.size(); ++i) {
            set.insert(nums[i]);
        }
        int longestSequence = 0;
        for (const auto& num : set) {
            // If num-1 does not exist in set
            if (!set.count(num - 1)) {
                int currentNum = num;
                int currentSequence = 1;
                // Find num + 1.....
                while (set.count(currentNum + 1)) {
                    currentNum += 1;
                    // Add one to the current currentSequence
                    currentSequence += 1;
                }
                longestSequence = max(currentSequence, longestSequence);
            }
        }
        return longestSequence;
    }
};
相关推荐
闪电悠米1 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
过期动态4 小时前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
Adios79413 小时前
设置交集大小至少为2
数据结构·算法·leetcode
流星白龙14 小时前
【Redis】7.Hash表
数据库·redis·哈希算法
FrameNotWork18 小时前
HarmonyOS 6.0 文件加密与安全存储:从哈希到硬件级密钥管理全链路实战
安全·哈希算法·harmonyos
程序猿乐锅21 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm1 天前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle1 天前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木1 天前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz1 天前
算法:回溯算法
c++·算法·leetcode