It use the hashset to do the tricks.

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         int len = num.size(), result = 0;
 5         if (len < 2) return len;
 6         unordered_set<int> sets;
 7         for (int i = 0; i < len; i++) {
 8             sets.insert(num[i]);
 9         }
10         while (!sets.empty()) {
11             int start = *sets.begin(), end = start;
12             while (sets.erase(start-1)) start--;
13             while (sets.erase(end)) end++;
14             result = max(result, end-start);
15         }
16         return result;
17     }
18 };

 

posted on 2015-03-20 07:25  keepshuatishuati  阅读(125)  评论(0编辑  收藏  举报