數組中最長的連續序列(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.

思路:

對於數組中任意元素K,找比它的數K+1,K+2,…和比它小的數K-1,K-2,…。這種連續序列的最大長度。

java實現

public int longestConsecutive(int[] num) {
        Set<Integer> set = new HashSet<Integer>();
        for(int n : num){
            set.add(n);
        }
        int max = 1;
        for(int n : num){
            if(set.remove(n)){
                int sum = 1;
                int small = n - 1;
                int big = n + 1;
                while(set.remove(small)){
                    sum++;
                    small--;
                }
                while(set.remove(big)){
                    sum++;
                    big++;
                }
                max = Math.max(sum, max);
            }
        }
        return max;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章