[leet code] 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.

===========

Analysis:

If we use Arrays.sort(), the problem would be pretty easy (just check array element one by one, if consecutive element than count+1; if not, reset count), the only thing that we should be careful about is the duplicated numbers case.  In this case, we can just skip the duplicated number. 

In the case of not sorting the array and time complexity limited as O(n), we should find a data structure that can find a given number in O(1).  So that each time we examine an element in original array, we need only O(1).  

Accordingly, we can copy the numbers in the given array into a HashSet (which can also exclude the duplicated numbers), then examine the each number in the given array.  In each examination, we check all its consecutive next number that exist in the hash set, and all its consecutive previous number that exist in the hash set.  From which we can get the whole serious of numbers for the examining array element.

To optimize the approach, we can remove the numbers that we have checked from the hash set.  Idea behind which is that each number in the hash set can only be in one consecutive elements sequence.

public class Solution {
    public int longestConsecutive(int[] num) {
        if (num.length == 0) return 0;
        if (num.length == 1) return 1;
        
        // copy unique numbers to a set
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i=0; i<num.length; i++) set.add(num[i]);
        
        int max = 1;
        for(int index=0; index<num.length; index++){
            if(set.contains(num[index])){ // examining number may has been removed from hash set
                int curr = num[index];
                int next = curr+1;
                int pre = curr-1;
                int count = 1;// current array element
                
                // find out all the next numbers
                while(set.contains(next)){
                    count++;
                    set.remove(next);
                    next++;
                }
                
                // find out all the previous numbers
                while(set.contains(pre)){
                    count++;
                    set.remove(pre);
                    pre--;
                }
                
                // keep the max count
                max = Math.max(max, count);
            }
        }
        
        return max;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章