zoukankan      html  css  js  c++  java
  • 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)

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

    set.remove()也很关键,可以不要,但是会严重影响runtime。加上以后每记录一个数就删除,避免后续重复被cue

  • 相关阅读:
    day31-python之内置函数
    day30-python之socket
    day28-python之property
    day27-python之迭代器协议
    day26-python之封装
    day25-python之继承组合
    初识AJAX
    写博客的心得
    web前端常见面试题
    学习网络安全的网站
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10509826.html
Copyright © 2011-2022 走看看