首页 > 代码库 > LeetCode Longest Consecutive Sequence

LeetCode Longest Consecutive Sequence

class Solution {public:    int longestConsecutive(vector<int> &num) {        int len = num.size();                int max_cons = 0;        int cur_cons = 0;                unordered_map<int, int> sgn;        unordered_map<int, int>::iterator iter;        for (int i=0; i<len; i++) {            sgn.insert(make_pair(num[i], 0x1));        }                for (int i=0; i<len; i++) {            iter = sgn.find(num[i]);            if (iter == sgn.end()) continue; // illegal case, should not hit            if (iter->second == 0) continue; // this range has been scaned            iter->second = 0;            cur_cons = 1;                        int try_n = num[i];            // search towards negative            while (try_n != INT_MIN) {                try_n--;                iter = sgn.find(try_n);                if (iter == sgn.end()) break;                iter->second = 0;                cur_cons++;            }            try_n = num[i];            // search towards positive            while (try_n != INT_MAX) {                try_n++;                iter = sgn.find(try_n);                if (iter == sgn.end()) break;                iter->second = 0;                cur_cons++;            }            if (cur_cons > max_cons) max_cons = cur_cons;        }                return max_cons;    }};

最直观的方法肯定是排序一下,然后从前到后扫描一遍即可,不过排序要nlogn时间,要在O(n)时间内完成的话,肯定不是基于比较排序了。可以使用桶排序,但是int的范围还是很大的,不可取。最后采用稀疏的表示方式,就是放入hash表中,第一次遍历数组插入以元素为key,1为value的hash表项,第二次遍历时尝试对每个元素的前驱后继值在hash表中进行一次查找,如果存在就继续向前或向后查找,更新连续计数cur_cons,同时将扫描到的连续hash表项的value值置零以表示该项已经进行了扫描,这样可以避免重复检测。