LeetCode week 13 : Longest Consecutive Sequence

题目

地址: https://leetcode.com/problems/longest-consecutive-sequence/description/
类别: Union Find
难度: Hard
描述:

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.

分析

给定含n个元素的无序整数数组,在O(n)时间复杂度内找出最长连续元素序列长度。
例:

Input:
[100, 4, 200, 1, 3, 2]
Output:
4([1, 2, 3, 4])

思路

最暴力的方法就是对每一个位置查看以它为起点的序列长度,如果每次都是直接遍历,时间复杂度为O(n3)。因此我们需要比较好的查找方式以及减少冗余的操作。
我们利用哈希表来存储这些元素,则建立哈希表时时间复杂度为O(n), 查找为O(1),所以最后时间复杂度为O(n)。

遍历nums[0…n-1],对每个元素nums[i]:

  • 若nums[i]-1在nums中,则不检查以nums[i]为起点的序列(避免冗余检查)
  • 若nums[i]-1不在nums中,则检查以nums[i]为起点的递增序列是否在nums中,当不在里面时停止查找,可得到以nums[i]为起点的最长递增序列长度

比较所有位置的最长序列长度得到最大值即为最后结果。

代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> hashSet(nums.begin(), nums.end());
        int maxLength = 0;
        int tail;
        for(int n : nums) {
            if(hashSet.find(n-1) == hashSet.end()) {
                tail = n + 1;
                while(hashSet.find(tail) != hashSet.end()) tail++;
                maxLength = max(maxLength, tail - n);
            } else {
                maxLength = max(maxLength, 1);
            }
        }
        return maxLength;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值