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.
Summary: The key idea is using hash map to record every number and their index.
1 int longestConsecutive(vector<int> &num) { 2 unordered_map<int, int> num_idx; 3 for(int i = 0; i < num.size(); i ++) { 4 num_idx[num[i]] = i; 5 } 6 7 vector<bool> visited; 8 for(int i = 0; i < num.size(); i ++) { 9 visited.push_back(false); 10 } 11 12 int longest_len = 0; 13 for(int i = 0; i < num.size(); i ++) { 14 if(visited[i] == true) 15 continue; 16 17 int tmp_len = 1; 18 visited[i] = true; 19 //increase 20 int value = num[i] + 1; 21 while(num_idx.find(value) != num_idx.end()){ 22 int index = num_idx[value]; 23 value ++; 24 visited[index] = true; 25 tmp_len ++; 26 } 27 //decrease 28 value = num[i] - 1; 29 while(num_idx.find(value) != num_idx.end()){ 30 int index = num_idx[value]; 31 value --; 32 visited[index] = true; 33 tmp_len ++; 34 } 35 36 if(tmp_len > longest_len){ 37 longest_len = tmp_len; 38 if(longest_len > num.size() / 2) 39 break; 40 } 41 } 42 43 return longest_len; 44 }