Longest Consecutive Sequence

来源:互联网 发布:linux wine运行qq 编辑:程序博客网 时间:2024/05/22 07:53

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. The key factors about a cluster is: lowest, highest, and length.
  2. Map lowest and highest to length. To merge two neighbor clusters, only need to update it's new lowest and highest, with new length.
  3. For every a[i], checking its neighbor a[i]-1 and a[i]+1 is enough.

Code in Java:

public class Solution {   public int longestConsecutive(int[] a) {    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();    int max = 1;    for (int i : a) {        if (map.containsKey(i)) continue;        map.put(i, 1);        if (map.containsKey(i - 1)) {            max = Math.max(max, merge(map, i-1, i));        }        if (map.containsKey(i + 1)) {            max = Math.max(max, merge(map, i, i+1));        }    }    return max;}private int merge(HashMap<Integer, Integer> map, int left, int right) {    int upper = right + map.get(right) - 1;    int lower = left - map.get(left) + 1;    int len = upper - lower + 1;    map.put(upper, len);    map.put(lower, len);    return len;}}


0 0