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

    [解题思路]

    数组,O(n)---->使用hash,空间换时间

    对于当前数N,我们检查N-1, N-2, N-3....N-K是否在hashmap中

    对于当前数N,我们检查N+1, N+2, N+3....N+j是否在hashmap中

    这里使用visited数组来记录已经访问过的数,这样减少检查次数,时间复杂度O(n)

    [Thoughts]
    Since it requires O(n) solution, normal sort won't be work here. Hash probably is the best choice.
    3 Steps:
    1. create the hashmap to hold <num, index>
    2. scan the num vector from left to right, for each num
                   i, check whether num -1 is in the map  (loop)
                  ii, check whether num+1 is in the map  (loop)
    3. track the sequence length during scanning.

    public class Solution {
        public int longestConsecutive(int[] num) {
            int len = num.length;
            Map<Integer, Integer> map = new HashMap<Integer,Integer>();
            
            for(int i = 0; i< len; i++){
                map.put(num[i],i);
            }
            
            int result = 0, count;
            int[] visited = new int[len];
            
            //这里使用visited数组来记录已经访问过的数,这样减少检查次数,时间复杂度O(n)
            for(int i = 0; i< len; i++){
                count =1 ;
                if(visited[i] == 1){
                    continue;
                }
                
                int index = num[i];
                visited[i] = 1;
                
                //注意 --index 先递减
                while(map.containsKey(--index)){
                    count++;
                    visited[map.get(index)] = 1;
                }
                // index 归位
                index = num[i];
                
                //注意 ++index 先递增
                while(map.containsKey(++index)){
                    count++;
                    visited[map.get(index)] = 1;
                }
                
                // result 记录之前的最大长度,与每次循环得到的长度相比,取最大
                if(count > result) result = count;
                
            }
            
            return result;
        }
    }

    ref: http://www.cnblogs.com/feiling/p/3265197.html

    http://fisherlei.blogspot.com/2013/02/leetcode-longest-consecutive-sequence.html

  • 相关阅读:
    Javascript文件加载:LABjs和RequireJS
    【译】前端开发者的基本要求
    正则基础之——NFA引擎匹配原理
    JavaScript 设计模式 安全沙箱模式
    jsdoc_toolkit
    JS判断手机浏览器
    JavaScript:Object.prototype.toString方法的原理
    FullCalendar 官方文档翻译2
    浏览器缓存机制
    jQuery.extend 函数详解
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3537449.html
Copyright © 2011-2022 走看看