Sunday, May 10, 2015

Longest Consecutive Sequence

来源:Leetcode

原帖:https://oj.leetcode.com/problems/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.

代码:
 class Solution {  
 public:  
   int longestConsecutive(vector<int> &num) {  
     unordered_set<int> s;  
     for (auto e : num) s.insert(e);    
     int res = 0;      
     for (int i = 0; i < num.size() && !s.empty(); ++i) { // using hash-set  
       if (!s.count(num[i])) continue;  
       int upper = num[i], lower = num[i];  
       while (s.find(upper) != s.end()) s.erase(upper++);          
       while (s.find(lower-1) != s.end()) s.erase(--lower);          
       res = max(res, upper - lower);  
     }  
     return res;  
   }  
 };  

No comments:

Post a Comment