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.

    For example,
    Given [100, 4, 200, 1, 3, 2],
    The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

    Your algorithm should run in O(n) complexity.

    此题有三种解法,第一种是用hashmap来做,遍历一次数组元素,遍历到数组某一值时,将该值赋予与他相连的其他元素+1值,即为元素个数,代码如下:

    public class Solution {

        public int longestConsecutive(int[] nums) {

            int res = 0;

            Map<Integer,Integer> map = new HashMap<>();

            for(int n:nums){

                if(!map.containsKey(n)){

                    int left = map.getOrDefault(n-1,0);

                    int right = map.getOrDefault(n+1,0);

                    int sum = left+right+1;

                    map.put(n,sum);

                    res = Math.max(res,sum);

                    map.put(n-left,sum);

                    map.put(n+right,sum);

                }

            }

            return res;

        }

    }

    第二种做法是使用hashset来做,一次性把数组元素全部放在set里面,然后遍历数组或者set,遍历到某一值时候,检查是否有该值-1,即检查最小值,然后找到最大值,做差就是长度,代码如下:

    public class Solution {

        public int longestConsecutive(int[] nums) {

            int res=0;

            Set<Integer> set = new HashSet<Integer>();

            for(int i:nums){

                set.add(i);

            }

            for(int n:nums){

                if(!set.contains(n-1)){

                    int m = n+1;

                    while(set.contains(m)){

                        m++;

                    }

                    res = Math.max(res,m-n);

                }

            }

            return res;

        }

    }

  • 相关阅读:
    小程序对于华为Oppo的canvas二维码渲染数据量大
    SonarQube代码质量管理工具的升级(sonarqube6.2 + sonar-scanner-2.8 + MySQL5.6+)
    SonarQube代码质量管理工具安装与使用(sonarqube5.1.2 + sonar-runner-dist-2.4 + MySQL5.x)
    在try-catch机制优化IO流关闭时,OutputStreamWriter 数据流被截断
    Java中日期格式化SimpleDateFormat类包含时区的处理方法
    彻底删除mysql服务(清理注册表)
    PHP7新特性的介绍
    RESTful架构详解
    php-config 介绍
    用 phpize 编译共享 PECL 扩展库
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6364772.html
Copyright © 2011-2022 走看看