简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
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.
» Solve this problemBecause it has to be solved in O(n) time. Thus, normal sorting algorithm cannot be applied here. So hashmap came to my mind, to quick allocate the element.
Algorithm:
1. Create a hashmap to store the given sequence
2. Create a vector to mark visited elements and avoid duplicate search
3. search num[i] +1 and num[i]-1 iteratively, and set count.
4. Return the longest length we found.
you solution is not O(n),
ReplyDeletesince a single elements might get visited many times unless you remove them from hashmap when you visit them first time.