My simple solution using unordered set 24ms, just sharing :)


  • 0
    R
    class Solution {
    

    public:
    int longestConsecutive(vector<int>& nums) {

     int i, n, k, a;
     unordered_set<int> myset;
     n = nums.size();
     
     for(i = 0; i < n; i++) {
         myset.emplace(nums[i]);
     }
     
     int currmax, max = 1;
     
     auto it = myset.begin();
     
     while(!myset.empty()) {
         currmax = 0;
         a = *it;
         k = 1;
         
         while(it != myset.end()) {
             myset.erase(it);
             it = myset.find(a+k);
             currmax++, k++;
         }
         
         k = 2;
         it = myset.find(a-1);
         
         while(it != myset.end()) {
             myset.erase(it);
             it = myset.find(a-k);
             currmax++, k++;
         }
         
         if(currmax > max)
            max = currmax;
        
         if(myset.size() < max)
            break;
            
         it = myset.begin();
     }
     return max;
    }
    

    };


Log in to reply
 

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