Monday, March 18, 2013
Longest Consecutive Sequence
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.
import java.util.*;
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
Set<Integer> buf = new HashSet<Integer>();
for(int i : num){
buf.add(i);
}
int start = 0;
int end = 0;
int ret = 0;
while(!buf.isEmpty()){
int v = buf.iterator().next();
start = v;
end = v;
buf.remove(v);
while(buf.contains(end+1)){
buf.remove(end+1);
end ++;
}
while(buf.contains(start-1)){
buf.remove(start-1);
start --;
}
ret = Math.max(ret, end - start +1);
}
return ret;
}
}
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
Given two words ( start and end ), and a dictionary, find the length of shortest transformation sequence from start to end , such tha...
No comments:
Post a Comment