128. 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)时间,通常要用map,这里每次到一个数,向前看+1数是否存在,向后看-1数是否存在,如存在,则继续滚动,length++。

时间和空间复杂度都是O(n)

public class Solution {
  public int longestConsecutive(int[] nums) {
    Map<Integer, Boolean> map = new HashMap<>();
    for (int n : nums) {
      map.put(n, false);
    }
    int maxLength = 0;
    for (int n : nums) {
      if (map.get(n)) {
        continue;
      }
      int i = n + 1;
      int length = 1;
      while(map.containsKey(i)) {
        map.put(i, true);
        length++;
        i++;
      }
      i = n - 1;
      while(map.containsKey(i)) {
        map.put(i, true);
        length++;
        i--;
      }
      if (length > maxLength) {
        maxLength = length;
      }
    }
    return maxLength;
  }
}

posted on 2015-04-30 00:36  shini  阅读(98)  评论(0编辑  收藏  举报

导航