Leetcode 128. Longest Consecutive Sequence
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
Example:
nums = [100, 4, 200, 1, 3, 2]
4
(The longest consecutive elements sequence is [1, 2, 3, 4]
and its length is 4.)Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
import java.util.HashSet;
import java.util.Set;
public class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
if (nums.length == 0) return 0;
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int longestStreak = 0;
for (int num : numSet) {
if (!numSet.contains(num - 1)) { // only look for the start of a sequence
int currentNum = num;
int currentStreak = 1;
while (numSet.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
public static void main(String[] args) {
LongestConsecutiveSequence solution = new LongestConsecutiveSequence();
int[] nums = {100, 4, 200, 1, 3, 2};
System.out.println(solution.longestConsecutive(nums)); // Output: 4
}
}
num - 1
is not in the Set).Thus, the overall time complexity is O(n), where n
is the number of elements in the array. The space complexity is also O(n) due to the extra space required for the HashSet.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?