Thursday, April 24, 2014

LeeCode: 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.

Analysis:

This is a typical problem to solve by sacrificing space to buy time. Since it is required O(n) complexity, we cannot simply sort it with common sorting algorithms. Borrowed the smart idea of using two unordered_map (representing a range with first and last) and the most neat coding style:

No comments:

Post a Comment