Topic
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
for example,
given [100, 4, 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.
Test instructions
given an unordered array of integers. Find the longest consecutive integer string sequence. and returns the length. Complexity requirements O (n)
Ideas
O (n) is not necessarily one pass, there is always such a fixed mind in the mind, you dug a hole for themselves. O (kn) is also O (n), only k is constant.
To find sequential strings and not to sort, we construct a class list structure to string together successive numbers.
So how to string it? Very obviously, given a number n. Then we need to know his previous number prev and its last number next whether it exists, assuming that we can string to prev or next, assuming that there is no continuous string on the end of the bird. We use a map to represent such a forward and backward relationship.
prev=n-1; next=n+1; Assume that n is present in the array. Then Map[n]=1
Assuming Prev is also in the array, then map[prev]=1, otherwise map[prev]=0
Assuming next is also in the array, then map[next]=1, otherwise map[next]=0
We scan the array two times:
The first scan is the relationship map we generated before and after
The second scan uses the back-and-forth relationship to recover successive strings, and the corresponding number of map[i in the recovery process is set to 0 to avoid repeated recovery.
Code
Class Solution {public: int longestconsecutive (vector<int> &num) { int size=num.size (); if (size==0) return 0; The first scan establishes the relationship map map<int, int> exist; for (int i=0; i<size; i++) { exist[num[i]]=1; if (exist[num[i]-1]!=1) exist[num[i]-1]=0; if (exist[num[i]+1]!=1) exist[num[i]+1]=0; } Scan int maxlength=0 twice; for (int i=0; i<size; i++) { if (exist[num[i]]==1) { //recover string int length=1; int number=num[i]-1; while (exist[number]==1) {length++; exist[number]=0; number--;} number=num[i]+1; while (exist[number]==1) {length++; exist[number]=0; number++;} if (length>maxlength) maxlength=length; } } return maxLength;} ;
Leetcode:longest consecutive Sequence [128]