Really simple and straightforward C++ solution with O(n) time


  • -1
    Z
    int longestConsecutive(vector<int> &num) {
        if(num.empty()){
            return 0;
        }
        unordered_set<int> set;
        for(int i = 0; i < num.size(); i++){
            set.insert(num[i]);
        }
        int maxLength = 0;
        while(!set.empty()){
            int length = 1;
            unordered_set<int>::iterator seed = set.begin();
            for(int i = *seed;; i--){
                if(set.find(i - 1) != set.end()){
                    length++;
                    set.erase(i - 1);
                }
                else{
                    break;
                }
            }
            for(int i = *seed;; i++){
                if(set.find(i + 1) != set.end()){
                    length++;
                    set.erase(i + 1);
                }
                else{
                    break;
                }
            }
            set.erase(*seed);
            maxLength = max(maxLength, length);
        }
        return maxLength;
    }

  • 0
    C

    for(int i = 0; i < num.size(); i++){
    set.insert(num[i]);
    }

    this use time n*lg(n)


  • 0
    Z

    can you explain why?


  • 0
    C

    sorry I make a mistake


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.