
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.
- We check whether a number a is consecutive by checking whether a-1 or a+1 is in the array.
- We need to record the count of consecutive numbers until the current number.
- We also need to update records, but we only need to update the border of the consecutive numbers.
-
How do we get the border? Just use the records of a-1 and a+1.
-
So it is a dynamic programming problem,
- the subproblem is checking whether each number a has a-1 or a+1.
- the dp structure is a hash table because the array is unsorted and has duplicate numbers.
- the hash table is used to record the count of consecutive numbers until each distinct number.
- Because the record is added step by step, so we only need to update the border of the consecutive numbers.
1 |
int longestConsecutive(vector<int>& nums) { |




近期评论