[Leetcode] 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.

使用容器实现。已经判断过的不用再次判断。

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         map<int, int> mp;
 5         for (int i = 0; i < num.size(); ++i) {
 6             mp[num[i]] = 1;
 7         }
 8         int len = 0, tmp;
 9         for (int i = 0; i < num.size(); ++i) {
10             tmp = 1;
11             if (mp[num[i]] == 1) {
12                 int left = num[i] - 1;
13                 while (mp.count(left) && mp[left] == 1) {
14                     mp[left--] = 0;
15                     ++tmp;
16                 }
17                 int right = num[i] + 1;
18                 while (mp.count(right) && mp[right] == 1) {
19                     mp[right++] = 0;
20                     ++tmp;
21                 }
22                 len = (len > tmp) ? len : tmp;
23             }
24         }
25         return len;
26     }
27 };

 

posted @ 2014-04-29 17:13  Eason Liu  阅读(178)  评论(0编辑  收藏  举报