Saturday, January 10, 2015

LeetCode 128: 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.
public class Solution {
    public int longestConsecutive(int[] num) {
        // Adopt HashSet, the time complexity of add and remove element is constant.
        // Test every starting element of consecutive elements
        int n = num.length;
        
        if (n == 0)
            return 0;

        if (n == 1)
            return 1;
         
         Set<Integer> set = new HashSet<>();
         
         for (int i : num)
            set.add(i);

        int max = 1; // If n >= 1, there are at least 1 consecutive element.
        int count; // Count the length of consecutive elements
        
        for (int i : num)
        {
            if (!set.contains(i-1) && set.contains(i+1))
            {
                int j = i+2;
                count = 2;
                
                while (set.contains(j))
                {
                    count++;
                    j++;
                }
                
                max = Math.max(max, count);
            }
        }
                
        return max; 
    }
}

No comments:

Post a Comment