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 shold run in O (N) Complexity.
If you sort the array first, and then traverse the sorted array, you can get the longest consecutive sequence. However, the time complexity of this operation is O (nlogn), which does not meet the requirements. If the time complexity is O (n), the space must be used for the time. A hash table is a commonly used space for time change. Here, the leetcode-cppexample method is used. Use a hash table used to record whether an element is used in consecutive sequence. For the numbers that are not used in the current consecutive sequence, we use them as the center image to expand left and right until they are not continuous. In this process, the continuous length is recorded. This method has its own personality. As long as we use a number in a consecutive sequence, other numbers in this consecutive sequence will also be used (because we will take a number as the center, such as expansion on both sides until discontinuous), so the entire algorithm is two pass (the first pass creates a hash table, and the second pass finds the longest consecutive sequence), so the time complexity is O (n ). The Code is as follows:
1 class Solution { 2 public: 3 int longestConsecutive(vector<int> &num) { 4 unordered_map<int,bool> used; 5 for(auto i:num)used[i] = false; 6 int longest = 0; 7 for(auto i:num){ 8 if(used[i]) continue; 9 int length = 1;10 used[i] = true;11 for(int j = i+1; used.find(j) != used.end(); j++){12 used[j] = true;13 length++;14 }15 for(int j = i-1; used.find(j) != used.end(); j--){16 used[j] = true;17 length++;18 }19 if(length > longest) longest = length;20 }21 return longest;22 }23 };