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;
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/