力扣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;
    }
};
相关推荐
蒟蒻小袁22 分钟前
力扣面试150题--全排列
算法·leetcode·面试
緈福的街口2 小时前
【leetcode】2236. 判断根节点是否等于子节点之和
算法·leetcode·职场和发展
祁思妙想2 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
薰衣草23332 小时前
一天两道力扣(2)
算法·leetcode
chao_7892 小时前
二分查找篇——寻找旋转排序数组中的最小值【LeetCode】
python·线性代数·算法·leetcode·矩阵
zstar-_3 小时前
【算法笔记】6.LeetCode-Hot100-链表专项
笔记·算法·leetcode
偷偷的卷5 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
s153357 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔7 小时前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七7 小时前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算