128. Longest Consecutive Sequence

本文深入探讨了如何在未排序整数数组中寻找最长连续元素序列的问题,提出了一个时间复杂度为O(n)的高效算法解决方案。通过使用哈希表进行高效查找,遍历数组并动态调整以找到最长连续序列,最终返回该序列的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

128. Longest Consecutive Sequence

Hard

2363134FavoriteShare

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Accepted

244,769

Submissions

566,263

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res=0;
        unordered_set<int> st;//哈希表实现查找非常高效,因为unordered底层是哈希表实现
        for(int i=0;i<nums.size();i++) st.insert(nums[i]);
        for(int val:nums){//遍历vector
        	if(st.find(val)==st.end()) continue;
        	st.erase(val);
        	int pre=val-1,pos=val+1;
        	while(st.find(pre)!=st.end()) st.erase(pre--);
        	while(st.find(pos)!=st.end()) st.erase(pos++);
        	res=max(res,pos-pre-1);
        }
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值