Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
Key to solve: HashSetIn order to archive O(N) => use space to reduce time complexity
Create a Set that including non-duplicated number from num array
Check the the Consecutive Sequence both decreasing and increasing order
public class Solution {
public int longestConsecutive(int[] num) {
if(num.length==0) return 0;
int maxCount=0;
HashSet set=new HashSet();
//initial the HashSet with num array
for(int n:num){
set.add(n);
}
int temp;
for(int n:num){
set.remove(n);
int count=1;
//check for decreasing connective
temp=n;
while(set.contains(temp-1)){
temp--;
count++;
set.remove(temp);
}
//check for increasing connective
temp=n;
while(set.contains(temp+1)){
temp++;
count++;
set.remove(temp);
}
maxCount=Math.max(maxCount,count);
}
return maxCount;
}
}