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.

题意:给出一个无序数组,求这个无序数组中最大的连续数组长度,要求时间复杂度是O(n)。

思路:自己没有想到解题思路,参考的是http://www.cnblogs.com/grandyang/p/4276225.html给出的解法。用set标记全部元素,然后遍历数组,找每个元素的最左和最右,找的部分都从set中移除,然后求左右边界差值,更新最大长度。

public int longestConsecutive(int[] nums) {
    int res = 0;
    if (nums == null || nums.length == 0) {
        return res;
    }

    HashSet set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    for (int num : nums) {
        if (set.remove(num)) {
            int left = num - 1;
            while (set.remove(left)) {
                left--;
            }
            int right = num + 1;
            while (set.remove(right)) {
                right++;
            }
            res = Math.max(res, right - left - 1);
        }
    }

    return res;
}

你可能感兴趣的:(Leetcode 128. Longest Consecutive Sequence)