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.
https://oj.leetcode.com/problems/longest-consecutive-sequence///Author:chao zeng//Date:2015-3-30class Solution {public:int longestconsecutive (vector<int> &num) {map<int,int> MP; const int NUM = 100;//because there is a negative number in the data, the array element is given an offset, guaranteeing the array subscript validity int length = Num.size (); for (int i = 0; i < length; i++) {mp[num[i] + num] = 1; } int ans; int res = 0; for (int i = 0; i < length; i++) {ans = 1; if (Mp.count (num[i] + num)) {int left = Num[i] + NUM-1; while (Mp.count (left) && mp[left]! = 0) {mp[left--] = 0; ans++; } int right = Num[i] + num + 1; while (Mp.count (right) && mp[right]! = 0) {mp[right++] = 0; ans++; }} if (res < ans) {res = ans; } } return res; }};
Leetcode:longest consecutive Sequence