Longest Consecutive Sequence
Med Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity.
Thoughts
看到longest seq 想到了DP。f[i]设为以i为尾的最长连续子序列的长度。由于没有排序,我们需要一种数据结构能O(1)时间查询之前访问过的元素中有没有是nums[i]前辈的,也就是hash set了。这时发现其实只要稍微操作一下set而不用真的使用DP. 先把所有元素放入set中,然后重新遍历nums,然后依次删除nums[i]的前后相连所有元素并计数即可。
Code
Analysis
每个元素出入set一次,总耗时O(n), 空间O(n).
Last updated
Was this helpful?