Longest Consecutive Sequence解题报告

Description:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.

Example:

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Link:

https://leetcode.com/problems/longest-consecutive-sequence/description/

解题方法:

这道题要求在O(n)时间解出,所以不能对数组进行排序。
解题思路参考:https://blog.csdn.net/fightforyourdream/article/details/15024861
O(n)解法为:把所有数都存到hashset中去,每遇到一个数,就把比它大的和比它小的连续的数都找一遍,在找的过程中把这些数都从hashset中删掉,防止重复查找。
比如例子:100, 4, 200, 1, 3, 2都加入hashset
当找100时,把100删掉,此时hashset: 4, 200, 1, 3, 2
.
.
.
当找到4时,找完以后的hashset: 200 (100在第一轮被删掉,1 2 3都在找比4小的连续数过程中都被删掉)

Time Complexity:

O(N)

完整代码:

int longestConsecutive(vector<int>& nums) {
    unordered_set<int> hash;
    for(int i: nums)
        hash.insert(i);
    int result = 0;
    for(int i: nums) {
        int cnt = 1;
        hash.erase(i);
        int temp = i - 1;
        //find less
        while(hash.find(temp) != hash.end()) {
            cnt++;
            hash.erase(temp--);
        }
        temp = i + 1;
        while(hash.find(temp) != hash.end()) {
            cnt++;
            hash.erase(temp++);
        }
        result = max(result, cnt);
    }
    return result;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容