[leetcode] longest consecutive sequence

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.

这题我的第一反应是bitmap,但mapping过去之后,怎么搜这个bitmap又是一个很大的问题。

其实用hash就可以了,首先把数组放在hash表里, O(n)

从表里拿到一个元素之后查找它的前后元素在不在hash表中,找到了把当前元素删除。

每次查找和删除都是O(1),所以hash表的遍历复杂度也是O(n)

顺便贴一下STL里面hash删除的用法

by position (1)
iterator erase ( const_iterator position );
by key (2)
size_type erase ( const key_type& k );
range (3)
iterator erase ( const_iterator first, const_iterator last );
Versions (1)  (3) 返回被删除元素的下一个元素的iterator
Version (2) 返回被删除的元素个数


class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unordered_set<int> hash;
        
        for(int i = 0; i < num.size(); i++){
            hash.insert(num[i]);
        }
        
        int ret = 0;
        int cnt;
        
        unordered_set<int>::iterator it;
        int cur_elem;
        int tmp_elem;
        
        while(!hash.empty()){
            it = hash.begin();
            cur_elem = *it;
            hash.erase(it);
            
            tmp_elem = cur_elem;
            cnt = 1;
            
            while((it = hash.find(tmp_elem + 1))!= hash.end()){
                hash.erase(it);
                tmp_elem++;
                cnt++;
            }
            
            tmp_elem = cur_elem;
            while((it = hash.find(tmp_elem - 1))!= hash.end()){
                hash.erase(it);
                tmp_elem--;
                cnt++;
            }
            
            ret = max(ret, cnt);
        }
        
        return ret;
    }
};


你可能感兴趣的:(LeetCode)