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.
Thought 1 & AC code first I want to sort the array and then look for it. The specific steps are as follows: array sorting considers three situations: (1) the next value is equal to the current value + 1 (2) the next value is equal to the current value (3) Other
AC code
public class Solution { public int longestConsecutive(int[] num) { if (num == null || num.length == 0) { return 0; } Arrays.sort(num); int len, tmp, i; for (len = tmp = i = 0; i + 1 < num.length; i++) { if (num[i + 1] - num[i] == 1) { tmp++; } else if (num[i + 1] == num[i]) { // do nothing } else { if (tmp > len) { len = tmp; } tmp = 0; } } if (tmp > len) { len = tmp; } return len + 1; }}
To analyze this question, we first use the system sorting function, Arrays. sort (), regardless of how the system functions are optimized, we can determine that the time complexity is greater than O (n), generally O (nlogn)
Idea 2 & AC code when the complexity of O (n) is required and the array is not sorted, we should consider using HashSet to exclude duplicate elements first, and the time complexity of searching elements is O (1)
AC code
public class Solution { public int longestConsecutive(int[] num) { if (num == null || num.length == 0) { return 0; } HashSet
set = new HashSet
(); for (int i = 0; i < num.length; i++) { set.add(num[i]); } int res = 0; for (int i = 0; i < num.length; i++) { if (set.contains(num[i])) { set.remove(num[i]); int tmp = 1; int next = num[i] + 1; while (set.contains(next)) { set.remove(next); next++; tmp++; } next = num[i] - 1; while (set.contains(next)) { set.remove(next); next--; tmp++; } res = Math.max(tmp, res); } } return res; }}