Longest consecutive sequence
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.
[Note]: There are several pitfalls in this question:
Trap 1: The array elements may be repeated, for example,-, and 2. The result is 4. Your sister's
Pit2: negative numbers are allowed. This should not be considered.
Pit3: The large number may be integer. min_value. Therefore, when sorting by count, consider overflow.
Algorithm ideas:
Train of Thought 1: Count sorting; linear sorting algorithm, and then find the longest continuous sequence length.
No bug-free is implemented, so no post is made.
Idea 2: divergence method. If you encounter a number, you want to scatter the two ends and maintain the maximum length.
1 public class Solution { 2 public int longestConsecutive(int[] num) { 3 if (num == null || num.length == 0) 4 return 0; 5 Set<Integer> set = new HashSet<Integer>(); 6 int max = 1; 7 for (int tem : num) { 8 set.add(tem); 9 }10 for (int tem : num) {11 if (set.contains(tem)) {12 set.remove(tem);13 int len = 1;14 int post = tem + 1;15 while (set.contains(post)) {16 set.remove(tem);17 post++;18 len++;19 max = Math.max(max, len);20 }21 int pre = tem - 1;22 while (set.contains(pre)) {23 set.remove(pre);24 pre--;25 len++;26 max = Math.max(max, len);27 }28 }29 }30 return max;31 }32 33 }
It can also be implemented using recursion. Big Data efficiency is a little lower, and it is no longer implemented. The time and space complexity are O (n ).