[leetcode] 128. Longest Consecutive Sequence

原创 2016年05月30日 11:33:28

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.

这道题是找未排序数组中最长连续序列的长度,题目难度为Hard。


题目限定时间复杂度O(n),所以不能sort之后通过遍历求结果,考虑到Hash Table的插入、查找等操作平均时间复杂度理论上能达到O(1),所以这里用Hash Table来解决问题。遍历数组,将遍历到的数字从Hash Table中删除,然后以此数字为准向左右逐个减1加1查看相邻数字是否在Hash Table中,在Hash Table中的数字也从Hash Table中删除,直至相邻数字不在Hash Table中,这样就找到了一个连续序列,拿此序列长度和最大序列长度比较并更新最大序列长度。通过以上方法遍历完数组即可得到最长连续序列长度。具体代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> hash(nums.begin(), nums.end());
        int ret = 1;
        
        for(auto num:nums) {
            if(hash.find(num) == hash.end()) continue;
            int cnt = 1;
            int curNum = num;
            hash.erase(num);
            while(hash.find(curNum-1) != hash.end()) {
                ++cnt;
                hash.erase(--curNum);
            }
            curNum = num;
            while(hash.find(curNum+1) != hash.end()) {
                ++cnt;
                hash.erase(++curNum);
            }
            ret = max(ret, cnt);
        }
        
        return ret;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode 128. Longest Consecutive Sequence

题目描述: Given an unsorted array of integers, find the length of the longest consecutive elements seq...

leetcode_question_128 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. ...
  • doc_sgl
  • doc_sgl
  • 2013年09月20日 14:24
  • 1267

【LeetCode】128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

LeetCode 128 Longest Consecutive Sequence

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

Longest Consecutive Sequence - LeetCode 128

题目描述: Given an unsorted array of integers, find the length of the longest consecutive elements sequ...
  • bu_min
  • bu_min
  • 2015年05月27日 08:22
  • 249

LeetCode Algorithms 128. Longest Consecutive Sequence 题解

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

[LeetCode]128.Longest Consecutive Sequence

Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longes...

Leetcode_128_Longest Consecutive Sequence

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43854597 Given an unsorted...

LeetCode: Longest Consecutive Sequence [128]

【题目】 Given an unsorted array of integers, find the length of the longest consecutive elements seque...

LeetCode128—Longest Consecutive Sequence

LeetCode128—Longest Consecutive Sequence
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[leetcode] 128. Longest Consecutive Sequence
举报原因:
原因补充:

(最多只允许输入30个字)