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

Problem: 128. 最长连续序列

文章目录

题目描述

思路

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

2.欲找出最长连续序列(先定义两个int变量longestSequence和currentSequence用于记录最长连续序列和当前最长序列),我们可以在遍历给定数组时(当前遍历到的元素为nums[i])去set集合中查找nums[i] - 1,是否存在;若存在,直接遍历下一个nums中的元素;若不存在则持续查找nums[i] + 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;
    }
};
相关推荐
TracyCoder12326 分钟前
LeetCode Hot100(8/100)—— 438. 找到字符串中所有字母异位词
算法·leetcode
June bug1 小时前
(#数组/链表操作)最长上升子序列的长度
数据结构·程序人生·leetcode·链表·面试·职场和发展·跳槽
hadage2331 小时前
--- 力扣oj柱状图中最大的矩形 单调栈 ---
算法·leetcode·职场和发展
json{shen:"jing"}1 小时前
18. 四数之和
数据结构·算法·leetcode
多米Domi0112 小时前
0x3f 第42天 复习 10:39-11:33
算法·leetcode
议题一玩到2 小时前
#leetcode# 1984. Minimum Difference Between Highest and Lowest of K Scores
数据结构·算法·leetcode
漫随流水2 小时前
leetcode回溯算法(90.子集Ⅱ)
数据结构·算法·leetcode·回溯算法
June bug2 小时前
(#数组/链表操作)合并两个有重复元素的无序数组,返回无重复的有序结果
数据结构·python·算法·leetcode·面试·跳槽
普贤莲花3 小时前
取舍~2026年第4周小结---写于20260125
程序人生·算法·leetcode
苦藤新鸡3 小时前
39.二叉树的直径
算法·leetcode·深度优先