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. 

    解决思路

    1. HashMap存储元素和对应的边界长度;

    2. 插入元素n时,检查n-1和n+1是否在map中,如果在,则更新边界的长度,最后输出最大长度即可。

    程序

    public class Solution {
        public int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            
            HashMap<Integer, Integer> map = new HashMap<>();
            int max = 1;
            
            for (int n : nums) {
                if (map.containsKey(n)) {
                    continue;
                }
                map.put(n, 1);
                if (map.containsKey(n - 1)) {
                    max = Math.max(max, updateLen(map, n - 1, n));
                }
                if (map.containsKey(n + 1)) {
                    max = Math.max(max, updateLen(map, n, n + 1));
                }
            }
            
            return max;
        }
        
        private int updateLen(HashMap<Integer, Integer> map, int a, int b) {
            int lower = a - map.get(a) + 1;
            int higher = b + map.get(b) - 1;
            int len = higher - lower + 1;
            map.put(lower, len); // update bound
            map.put(higher, len);
            return len;
        }
    }
    

      

  • 相关阅读:
    webpack学习(一)—— 入门
    AMD 规范
    CommonJS 规范
    webpack 故障处理
    webpack 开发环境
    webpack 插件
    webpack 配置文件
    webpack 使用
    webpack Loader
    webpack常用的插件安装命令
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4701454.html
Copyright © 2011-2022 走看看