1. Specific topics
To a given integer array unsorted, to find the length of the longest contiguous sequence. The time requirements of the algorithm complexity is O (n).
Example:
Input: [100, 4, 200, 1, 3, 2] Output: 4 explained: the longest contiguous sequence is [1, 2, 3, 4]. Its length is 4.
2. Analysis of ideas
As the title does not require a continuous sequence elements are ordered in the original array, for as long as a number to find out if there are several adjacent to the array, so consider an element into the HashSet achieve O (1) time query .
3. Code
1 public int longestConsecutive(int[] nums) { 2 HashSet set = new HashSet(); 3 int longest = 0; 4 for(int num : nums){ 5 set.add(num); 6 } 7 for(int num : nums){ 8 if(set.remove(num)){ 9 int count = 1; 10 int current = num; 11 while(set.remove(--current)) count++; 12 current = num; 13 while(set.remove(++current)) count++; 14 longest = Math.max(longest, count); 15 } 16 } 17 return longest; 18 }