数组中最长的连续序列(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 set = new HashSet();
        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;
    }

你可能感兴趣的:(数组)