runnig

[leetcode] 128 Longest Consecutive Sequence

Feb 17th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. /*
  2.  
  3. http://leetcode.com/onlinejudge#question_128
  4.  
  5. Longest Consecutive Sequence
  6. Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
  7.  
  8. For example,
  9. Given [100, 4, 200, 1, 3, 2],
  10. The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
  11.  
  12. Your algorithm should run in O(n) complexity.
  13.  
  14. */
  15.  
  16. class Solution {
  17. public:
  18.     int longestConsecutive(vector<int> &A) {
  19.        
  20.         const size_t N = A.size();
  21.        
  22.        
  23.         unordered_set<int> S;
  24.         unordered_set<int>::iterator it;
  25.        
  26.         unordered_set<int> visited;
  27.                
  28.         for(size_t i = 0; i < N; ++i)
  29.         {
  30.             S.insert(A[i]);    
  31.         }
  32.        
  33.         int maxsubseq = 0;
  34.        
  35.        
  36.         for(size_t i = 0; i < N; ++i)
  37.         {
  38.             if(visited.find(A[i]) != visited.end())
  39.             {
  40.                 continue;
  41.             }
  42.            
  43.             int curmax = A[i], curmin = A[i];
  44.            
  45.             while(S.end() != (it = S.find(curmax+1)))
  46.             {
  47.                 S.erase(it);                
  48.                 ++curmax;
  49.                 visited.insert(curmax);
  50.             }
  51.            
  52.             while(S.end() != (it = S.find(curmin-1)))
  53.             {
  54.                 S.erase(it);                
  55.                 --curmin;
  56.                 visited.insert(curmin);
  57.             }
  58.            
  59.             int subseq = curmax - curmin + 1;
  60.             maxsubseq = max(maxsubseq, subseq);
  61.         }
  62.         return maxsubseq;
  63.     }
  64. };
Advertisement
Add Comment
Please, Sign In to add comment