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.
Use the map template,
Map records the maximum continuous intervals. Use two keywords to search, from small to large, and from large to small
The main idea is that the newly added elements merge between two intervals, namely [..., A-1] a [A + 1.
Why can we get the optimal solution: greedy algorithm
Because every new element is merged as much as possible, and the maximum continuous interval containing the element is obtained.
using namespace std;class Solution {public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_map<int, bool> set; unordered_map<int, int> range; int max = 0; for(int i = 0; i < num.size(); i++) { if(!set[num[i]]) { set[num[i]] = 1; int left = num[i]; int right = num[i]; if(range.count(num[i] - 1) && range[num[i] - 1] <= num[i] - 1) { left = range[num[i] - 1]; range.erase(num[i] - 1); } if(range.count(num[i] + 1) && range[num[i] + 1] >= num[i] + 1) { right = range[num[i] + 1]; range.erase(num[i] + 1); } range[left] = right; range[right] = left; if(max < right - left + 1) max = right - left + 1; } } return max; }};