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.
Idea: The idea is to grow a consecutive elements sequence around each element. Without loss of generality, we first expand the sequence in increasing direction (keep plus 1), then expand in decreasing direction (keep minus 1).
Any elements belonging to the same consecutive sequence will generate the same result. For example, [100, 4, 200, 1, 3, 2], if we start from 4, we get 4, 4-1=3, 4-2=2, 4-3=1. If we start from 3, we have 3, 3+1=4, 3-1=2, 3-2=1. So we do not to grow sequences around the elements used before, this can be resolved by using a HashMap<value (integer), used or not (boolean)>.
Time: O(n) Space: O(n)
Code:
public class Solution {
public int longestConsecutive(int[] num) {
HashMap<Integer,Boolean> used=new HashMap<Integer,Boolean>();
for(int i:num)
used.put(i,false);
int result=0;
for(int i:num)
{
if(used.get(i)==true)
continue;
int big=i+1;
while(used.containsKey(big)&&used.get(big)==false)
{
used.put(big,true);
big+=1;
}
int small=i-1;
while(used.containsKey(small)&&used.get(small)==false)
{
used.put(small,true);
small-=1;
}
result=Math.max(result,big-small-1);
}
return result;
}
}
No comments:
Post a Comment