Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
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
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums){
set.add(num);
}
int maxCount = 0;
for (int num : nums){
int currentNum = num;
int currSequence = 1;
if (!set.contains(num - 1)){
while (set.contains(currentNum + 1)){
currentNum++;
currSequence++;
}
}
maxCount = Math.max(maxCount, currSequence);
}
return maxCount;
}
}
Time: O(n) Space: O(n)
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length==0) return 0;
Arrays.sort(nums); //[1,2,3,3,4,100,200]
int maxCount = 1;
int currentCount=1;
for(int i =1 ; i< nums.length; i++){
if(nums[i]-nums[i-1]==1){
currentCount++;
} else if (nums[i]!= nums[i-1]){
currentCount =1;
}
if(currentCount > maxCount){
maxCount = currentCount;
}
}
return maxCount;
}
}
Time: O(nlog(n)) Space: O(1)