码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Longest Consecutive Sequence

时间:2014-10-24 23:30:05      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   ar   for   sp   div   

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.

 

这题自己只做出个逗比版,用位向量来先标记一遍,然后在遍历位向量算出最长,这相当于是排序,不过空间消耗可能很大。。。因为位向量的大小是数组里最大那个元素,这个方法不能处理很大元素的情况,如果数组有个元素是100000,但是数组大小只是5,位向量依然要100000这么大。。。而且也不能处理负数的情况,所以是逗比版。

 

正常的解法就是所谓的空间换时间,用哈希表先把数组存下来耗时O(n),然后去遍历哈希表,拿出一个数然后把他升序和降序的连续数找出来移除并记录下他们的长度,然后与最大值比较并更新,这样当整个哈希表为空的时候最大值也找到了,复杂度亦是O(n)

int consecutive(unordered_set<int>& set, int value, bool asc) {
    int cnt = 0;
    while (set.find(value) != set.end()) {
        cnt++;
        set.erase(value);
        if (asc) {
            value++;
        }else {
            value--;
        }
    }
    return cnt;
}

int longestConsecutive(vector<int> &num) {
    int max = 0;
    unordered_set<int> set;
    for (int n: num) {
        set.insert(n);
    }
    for (int i = 0; i < num.size(); i++) {
        int value = num[i];
        int seq = consecutive(set, value, true) + consecutive(set, value-1, false);
        if (seq > max) max = seq;
    }
    return max;
}

 

另附逗比版...

bubuko.com,布布扣
int longestConsecutive_kidding(vector<int> &num) {
    int max = 0;
    for (int i=0; i<num.size(); i++) {
        if (max < num[i]) max = num[i];
    }
    vector<int> pos(max);
    
    for (int i = 0; i < max; i++) {
        pos[i] = 0;
    }
    
    for (int i = 0; i < num.size(); i++) {
        pos[num[i]] = 1;
    }
    
    int j = 0, l = 0;
    for (int i = 0; i < max; i++) {
        if (pos[i] == 1) {
            j++;
            if (j > l) l = j;
        }
        else {
            j = 0;
        }
    }
    
    return l;
}
逗比

 

[LeetCode] Longest Consecutive Sequence

标签:style   blog   http   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/agentgamer/p/4049470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!