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.

分析:主要用map来记录nums[i]是否检查过。检查过则从map中删除,同时检查nums[i] + 1和nums[i] - 1。

运行时间:40ms

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int>& nums) {
 4         map<int, int> hashmap;
 5         for(int i = 0; i < nums.size(); i++) hashmap.insert(map<int, int>::value_type(nums[i], i));
 6         
 7         int longest = 1;
 8         map<int, int>::iterator ite;
 9         for(ite = hashmap.begin(); ite != hashmap.end(); ite++){
10             int len = 1;
11             
12             int j = ite->first + 1;
13             for(; hashmap.find(j) != hashmap.end(); j++){
14                 len++;
15                 hashmap.erase(j);
16             }
17             int k = ite->first - 1;
18             for(; hashmap.find(k) != hashmap.end(); k--){
19                 len++;
20                 hashmap.erase(k);
21             }
22             longest = max(longest, len);
23         }
24         return longest;
25     }
26 };

 

你可能感兴趣的:(sequence)