Wednesday, June 11, 2014

LeetCode: 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.

Solution:

We use a bimap to keep the intervals, implemented with two hashmaps one that starts are mapped to ends and the other one viceversa.

public class Solution {
    public int longestConsecutive(int[] num) {
        int longest=0;
        HashMap<Integer, Integer> startToEnd = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> endToStart = new HashMap<Integer, Integer>();
        for(int i =0; i<num.length; i++)
        {
            int start = num[i];
            int end = num[i];
            if(endToStart.containsKey(num[i]))
            {
                start = endToStart.get(num[i]);
                startToEnd.remove(start);
                endToStart.remove(num[i]);
            }
            if(startToEnd.containsKey(num[i]))
            {
                end = startToEnd.get(num[i]);
                startToEnd.remove(num[i]);
                endToStart.remove(end);
            }
            if(endToStart.containsKey(num[i]-1))
            {
                start = Math.min(start, endToStart.get(num[i]-1));
                startToEnd.remove(start);
                endToStart.remove(num[i]-1);
            }
            if(startToEnd.containsKey(num[i]+1))
            {
                end = Math.max(end, startToEnd.get(num[i]+1));
                startToEnd.remove(num[i]+1);
                endToStart.remove(end);
            }
            startToEnd.put(start,end);
            endToStart.put(end,start);
            longest = longest < end- start + 1 ? end- start + 1 : longest;
        }
        return longest;
    }
}

No comments :

Post a Comment