128. Longest Consecutive Sequence

Difficulty:
Related Topics:
Similar Questions:

Problem

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.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
  var map = {};
  var max = 0;
  var start = 0;
  var end = 0;
  var num = 0;
  var len = nums.length;
  for (var i = 0; i < len; i++) {
    num = nums[i];
    if (map[num]) continue;
    start = map[num - 1] ? map[num - 1].start : num;
    end = map[num + 1] ? map[num + 1].end : num;
    map[num] = { start: num, end: num };
    map[start].end = end;
    map[end].start = start;
    max = Math.max(end - start + 1, max);
  }
  return max;
};

Explain:

num 为某连续序列的端点,map[num] 保存了连续序列的起点和终点。

Complexity: