[Question]
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 shocould run in O (n) complexity.
Question]
Given an unordered integer array, find the longest continuous integer string sequence and return the length. Complexity Requirements O (N)
[Idea]
O (n) is not necessarily one pass. There is always such a fixed mindset in his mind that he has dug a hole for himself. O (kN) is also O (N), as long as K is a constant.
To find continuous strings and not sort them, we need to construct a class list structure to concatenate continuous numbers. So how are strings? Obviously, given a number N, we need to know whether the previous number Prev exists with the next number. If so, we can concatenate the prev or next, if it does not exist, the bird will end with a continuous string. We use a map to represent this type of forward-backward relationship.
Prev = N-1; next = n + 1; if n is present in the array, map [N] = 1
If the prev is also in the array, map [Prev] = 1; otherwise, map [Prev] = 0
If next is also in the array, map [next] = 1; otherwise map [next] = 0
We scan the array twice:
The first scan is to generate the frontend and backend relationship map.
The second scan uses the frontend and backend relationships to restore consecutive strings. The 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; // 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;} // second scan int maxlength = 0; For (INT I = 0; I <size; I ++) {If (exist [num [I] = 1) {// restore 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 ;}};