Find the Length of Longest Consecutive Integer Sequence from Unsorted Array
package org.wesome.dsalgo;
import java.util.Arrays;
import java.util.HashSet;
public class longestSequence {
public static int longestSequence(int[] nums) {
final HashSet<Integer> hSet = new HashSet<>();
// Add all elements in HashSet
Arrays.stream(nums).forEach(num -> hSet.add(num));
int longest_sequence_len = 0;
for (int i : nums) { // loop all elements of array
int length = 1;
// check if list contains no less than current
for (int j = i - 1; hSet.contains(j); --j) {
hSet.remove(j);
++length;
}
// check if list contains no more than current
for (int j = i + 1; hSet.contains(j); ++j) {
hSet.remove(j);
++length;
}
longest_sequence_len = Math.max(longest_sequence_len, length);
}
return longest_sequence_len;
}
}