【Leetcode】128. Longest Consecutive Sequence

Description

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Discuss

可以使用散列表的方法来解这一题。先用一个hash把数据存起来,然后遍历数组的中每一个元素,如果该元素是连续子串的起始元素(通过判断前一个元素是否的set中),就依次计数,最后取最大值。

Code

class Solution {
    public int longestConsecutive(int[] a) {
        if (a == null || a.length == 0) { return 0; }
        Set<Integer> set = new HashSet<>();
        for (int num : a) {
            set.add(num);
        }

        int res = 0;
        for (int num : a) {
            if (!set.contains(num - 1)) {
                int ant = 0;
                while (set.contains(num)) {
                    ant++;
                    num++;
                }
                res = Math.max(res, ant);
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xiagnming/p/9390396.html