class Solution { public int longestConsecutive(int[] nums) { if (nums.length < 2) { return nums.length; } Set<Integer> set = new HashSet<>(); for (int num : nums) { set.add(num); } int length = 1; while (!set.isEmpty()) { int current = set.iterator().next(); int left = current; int right = current; set.remove(current); while (set.contains(left - 1)) { set.remove(left); left--; } while (set.contains(right + 1)) { set.remove(right); right++; } length = Math.max(right - left + 1, length); } return length; } }