-->

Monday, December 19, 2016

128. Longest Consecutive Sequence

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

Solution:
My first response is to sort the array first, but this question requests time complexity of O(n). So we may need some help from data structures, like hash table, set, ... Will use hash table, first to built up hash table; then scan the array again, for each element, will check the existence its neighbor in value with the help of hash table built.  Then find the longest one to return.

Code:
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        unordered_map<int, bool> m;
        for(auto i:nums) m[i] = true;//built up hash table (or map);
        for(auto i:nums){
            if(m[i]){
                int len = 1;
                int j = 1;
                while(m[i+j]){//search larger direction in value;
                    ++len;
                    m[i+j] = false;
                    ++j;
                }
                j = 1;
                while(m[i-j]){//search smaller direction in value;
                    ++len;
                    m[i-j] = false;
                    ++j;
                }
                m[i] = false;
                res = max(res, len);
            }
        }
        return res;
    }
}; 

No comments :

Post a Comment