zoukankan      html  css  js  c++  java
  • Longest Consecutive Sequence

    Longest Consecutive Sequence

    问题:

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

    思路:

      HashSet进行存储

    我的代码:

    public class Solution {
        public int longestConsecutive(int[] num) {
            if(num == null || num.length == 0)  return 0;
            Set<Integer> set = new HashSet<Integer>();
            for(int i = 0; i < num.length; i++)
            {
                set.add(num[i]);
            }
            int maxLen = 0;
            for(int i = 0; i < num.length; i++)
            {
                if(set.contains(num[i]))
                {
                    int tmp = num[i] - 1;
                    int len = 1;
                    set.remove(num[i]);
                    while(set.contains(tmp))
                    {
                        set.remove(tmp);
                        len++;
                        tmp--;
                    }
                    tmp = num[i] + 1;
                    while(set.contains(tmp))
                    {
                        set.remove(tmp);
                        len++;
                        tmp++;
                    }
                    maxLen = Math.max(maxLen,len);
                }
            }
            return maxLen;
        }
    }
    View Code

    学习之处:

      数组映射成,用HashSet进行存储可以在O(1)快速的查找任何一个数值

  • 相关阅读:
    上传项目到githug
    架构漫谈阅读笔记01
    连接清华镜像
    Java-Spark
    推荐系统
    数据湖技术
    如何做好架构划分
    构建之法阅读笔记 02
    构建之法阅读笔记01
    Tensorflow安装
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4330763.html
Copyright © 2011-2022 走看看