首页 > 其他 > 详细

Longest Consecutive Sequence--记录区间信息

时间:2018-07-16 22:55:06      阅读:273      评论:0      收藏:0      [点我收藏+]

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--记录区间信息

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!