Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
Test Cases
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Solution
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
set<int> numSet;
for(int n: nums) numSet.insert(n);
int longest = 0;
for(int n: numSet) {
if (!numSet.count(n-1)) {
int currentStreak = 1;
int currentNum = n;
while(numSet.count(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}
longest = max(longest, currentStreak);
}
}
return longest;
}
};
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int n: nums) set.add(n);
int longest = 0;
for(int n: set) {
if (!set.contains(n-1)) {
int currentStreak = 1;
int currentNum = n;
while(set.contains(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}
longest = Math.max(longest, currentStreak);
}
}
return longest;
}
}