zoukankan      html  css  js  c++  java
  • [LeetCode] 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.


    题意:给一个未排序数组,找出其中最长的连续串,要求复杂度O(n)
    其实题目给了半个提示,未排序,但是要求的复杂度又是O(n)级别的。由于这个是个纯乱序数组,而且没有什么特色的数组
    排序的话复杂度一定是O(nlogn)级别的,所以直接放弃排序
    这题可以开一个set去记录出现了哪些数字,然后从我们开始的某一点去向两边访问,如果有这个数字,就删除,然后不断维护长度就行了。
    举例:
    100, 3, 200, 1, 4, 2
    如果我们访问到了3,对其左右两边进行寻找,发现了1,2,4,然后这些数字就没必要再去访问了,因为他们可能产生的结果已经通过3解掉了
    class Solution {
        public int longestConsecutive(int[] nums) {
            if (nums.length == 0)
                return 0;
            Set<Integer> set = new HashSet<Integer>();
            for (int i = 0; i < nums.length; i++) {
                set.add(nums[i]);
            }
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < nums.length; i++) {
                if (set.contains(nums[i])) {
                    int len = 1; // 这个是因为我懒,这个变量可以不要,通过r和l就能计算了
                    int r = nums[i] + 1;
                    int l = nums[i] - 1;
                    while(set.contains(r)) {
                        set.remove(new Integer(r));
                        r ++;
                        len ++;
                    }
                    while(set.contains(l)) {
                        set.remove(new Integer(l));
                        l --;
                        len ++;
                    }
                    max = Math.max(len, max);
                }
            }
            return max;
        }
    }
     
  • 相关阅读:
    Oct 21st-
    ContextLoaderListener 解析
    HTTPS 证书制作及使用
    Spring MVC 源码分析
    思考
    《深入理解java虚拟机》 第七章虚拟机类加载机制
    《深入理解java虚拟机》第六章 类文件结构
    《深入理解java虚拟机》第三章 垃圾收集器与内存分配策略
    《深入理解java虚拟机》第二章 Java内存区域与内存溢出异常
    SSM-1第一章 认识SSM框架和Redis
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9864931.html
Copyright © 2011-2022 走看看