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;

        }

    }

  • 相关阅读:
    C#如何为程序打包发布应用(图解教程) (转)
    异步委托与多线程
    如何判断自己的WP7 SDK版本
    (转)c#实现WinRAR解压缩
    网页HTML代码大全
    byte[] ,image, bitmap之间的转换
    MS开发者应懂得知识
    StringFarmat控制字符串居中显示
    WP7模拟器的感应器和GPS模拟定位功能
    lucene.net搜索文档(pdf,doc,txt)内容
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6364772.html
Copyright © 2011-2022 走看看