longest-consecutive-sequence

本文介绍了一种寻找给定未排序整数数组中最长连续元素序列的算法,并提供了两种实现方法:一种使用额外向量进行统计,另一种利用无序集合进行高效查找与扩展。

题目简述

  • Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
  • For example,Given[100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.
  • Your algorithm should run in O(n) complexity.

  • 给定未排序的整数数组,找到最长连续元素序列的长度。例如,给定[100,4,2,1,3,2],最长的连续元素序列是[1,2,3,4]。 返回长度:4。您的算法应该以O(n)复杂度运行。

  • 方法一:(1)求取数组中的最大值maxValue;(2)利用桶思想,分配一个vector向量data,大小为maxValue。将数组中的元素作为下标,统计出现的数值。(3)统计连续序列的长度,遍历data即可。(空间复杂度过高)

#include<iostream>
#include<vector>

using namespace std;

int longestConsecutive(vector<int> &num) {
    int lens = num.size();
    if (lens<2)
        return lens;
    int maxValue = 0;
    for (int i = 0; i<lens; ++i) {
        if (maxValue<num[i])
            maxValue = num[i];
    }
    ++maxValue;
    vector<int> data(maxValue, 0);
    for (int i = 0; i<lens; ++i) {
        ++data[num[i]];
    }
    int maxCount = 0;
    int count = 0;
    for (int i = 0; i<maxValue; ++i) {
        if (data[i] == 0) {
            if (maxCount<count)
                maxCount = count;
            count = 0;
        }
        else {
            ++count;
        }
    }
    return maxCount;
}

int main(int argc, char* argv[]) {
    vector<int> vec{ 100,4,200,1,3,2 };
    cout << longestConsecutive(vec) << endl;
    getchar();
    return 0;
}
  • 方法二:利用无序set,向数值的两边扩充求解。
class Solution {
public:
    int longestConsecutive(vector<int>& num) {
        int lens=num.size();
        if(lens<2)
            return lens;
        unordered_set<int> s;
        for(int i=0;i<lens;++i){
            s.insert(num[i]);
        }
        int maxCount=0;
        for(int it:num){
            int sum=0;
            if(s.erase(it)){
                ++sum;
                int smallVal=it-1;
                int bigVal=it+1;
                while(s.erase(smallVal)){
                    ++sum;
                    --smallVal;
                }
                while(s.erase(bigVal)){
                    ++sum;
                    ++bigVal;
                }
                maxCount=max(maxCount,sum);
            }
        }
        return maxCount;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值