LeetCode 128. Longest Consecutive Sequence

来源:互联网 发布:淘宝店铺标志免费制作 编辑:程序博客网 时间:2024/06/04 01:16

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.

题目描述

给定一个非排序数组,求出最长连续序列。要求算法的时间复杂度为O(n)

解题思路

遍历一遍非排序数组,时间就要O(n)。想要在O(n)的时间内完成该算法,就需要我们在遍历到一个数据的时候,

查找与之连续的数字是否在该非排序数组中。遍历的时间复杂度已经是O(n),所以查找的时间复杂度只能是O(1),

因此,自然想到hash_set数据结构。

总体思路就是:取出hash_set中的首个元素,删除该元素,判断这个元素+1,-1是否在hash_set结构中

hash_set代码如下:

class Solution {public:    int longestConsecutive(vector<int>& nums) {        int ans = 0;        hahs_set<int> hs;        for(int i = 0; i < nums.size(); i++) {        hs.insert(nums[i]);    }    while(!hs.empty()) {    int val = *hs.begin();    int count = 1;    hs.erase(val);    for(int i = val + 1; hs.find(i) != hs.end(); ++i) {    count++;    hs.erase(i);    }    for(int i = val - 1; hs.find(i) != hs.end(); --i) {    count++;    hs.erase(i);    }    ans = max(ans,count);    }    return ans;    }};

提交之后发现编译错误 Compile Error

'hahs_set' was not declared in this scope

发现hash_set行不通,于是想尝试一下,直接使用set结构,对数据进行存储。

虽然set查找时间复杂度log(n),只是想尝试一下。结果竟然AC。

set代码如下

int longestConsecutive(vector<int>& nums) {    int ans = 0;    hash_set<int> hs;    for(int i = 0; i < nums.size(); i++) {    hs.insert(nums[i]);}while(!hs.empty()) {int val = *hs.begin();int count = 1;hs.erase(val);for(int i = val + 1; hs.find(i) != hs.end(); ++i) {count++;hs.erase(i);}for(int i = val - 1; hs.find(i) != hs.end(); --i) {count++;hs.erase(i);}ans = max(ans,count);}return ans;}

运行结果排名在39.15%

虽然通过,但是并不满足题目要求。因此就出查找hash_set为什么通不过。

网上查阅资料发现:hash_map,hash_set 等已经被废弃了,C++11用unordered_map,unordered_set等来替代。

于是就使用unordered_set代替hash_set。

unordered_set代码:

    int longestConsecutive(vector<int>& nums) {        int ans = 0;        unordered_set<int> hs;        for(int i = 0; i < nums.size(); i++) {        hs.insert(nums[i]);    }    while(!hs.empty()) {    int val = *hs.begin();    int count = 1;    hs.erase(val);    for(int i = val + 1; hs.find(i) != hs.end(); ++i) {    count++;    hs.erase(i);    }    for(int i = val - 1; hs.find(i) != hs.end(); --i) {    count++;    hs.erase(i);    }    ans = max(ans,count);    }    return ans;    }

从运行结果分析,效率明显优于set,且满足题目要求


有更好的想法,欢迎交流

0 0
原创粉丝点击