力扣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;
    }
};
相关推荐
smj2302_796826522 小时前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
青山木2 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
垆边人似月.2 小时前
字符串重排后最大字典序
算法·leetcode·职场和发展
代码什么用3 小时前
LeetCode-42. 接雨水
算法·leetcode
yi0115 小时前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
Navigator_Z7 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.8 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
longlongzihan8 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
kukubuzai9 小时前
二分查找系列一
数据结构·算法·leetcode