zoukankan      html  css  js  c++  java
  • 【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;
        }
    }
    
  • 相关阅读:
    开发日记1
    探索需求2
    探索需求1
    周总结8
    周总结7
    周总结6
    周总结5
    周总结4
    周总结3
    周总结2
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9390396.html
Copyright © 2011-2022 走看看