力扣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;
    }
};
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll6 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐6 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶6 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER6 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了6 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333336 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录6 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1236 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode