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;

        }

    }

  • 相关阅读:
    matlab 绘制条状图形
    细思恐极 天价房都被谁买去了?——如何操作?
    matlab中的containers.Map()
    林彪:怎样当好一个师长?
    matlab 怎么建立结构体数组?
    matlab中patch函数的用法
    Ubuntu 安装配置MySQL,并使用VS的Server Explorer UI界面远程管理MySQL
    CLIQUE 聚类算法以及Java实现+多线程
    R 中同步进行的多组比较的包:npmc
    基于D3JS绘制中国地图
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6364772.html
Copyright © 2011-2022 走看看