码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Consecutive Sequence--记录区间信息

时间:2018-07-16 23:11:51      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:lex   nta   and   longest   should   input   div   contain   val   

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

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Solution1: Sort it.

Solution2: Use hashmap to store consecutive intervals information, make sure the lowest and the highest both point to length of consecutive interval, such as [0,1,2,3,4], then (0->5, 4->5).

class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int max = 0;
        for (int n : nums) {
            if (map.containsKey(n)) continue;
            map.put(n,1);
            int a = map.getOrDefault(n-1,0), b = map.getOrDefault(n+1,0);
            int newval = a+b+1;            
            max = Math.max(max,newval);
            if (a == 0 && b == 0) continue; //no neighbor
            map.put(n-a,newval); //update lowest
            map.put(n+b,newval); //update highest
        }
        return max;
    }
}

 

Longest Consecutive Sequence--记录区间信息

标签:lex   nta   and   longest   should   input   div   contain   val   

原文地址:https://www.cnblogs.com/liudebo/p/9320727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!