128. Longest Consecutive Sequence

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了128. Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。

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.
class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i : nums) set.add(i);
        int res = 0;
        for(int i: nums){
            int len = 1;
            for(int j = i-1; set.contains(j); j--){
                len++;
                set.remove(j);
            }
            for(int k = i+1; set.contains(k); k++){
                len++;
                set.remove(k);
            }
            res = Math.max(len, res);
        }
        return res;
    }
}

划重点!HashSet的查找的效率是O(1),所以加上遍历才能达到O(n)

思想是以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。

以上是关于128. Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence