[Leetcode]128: Longest Consecutive Sequence

Link : https://leetcode.com/problems/longest-consecutive-sequence/

Problem :
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

圖來自leetcode

Thoughts :
1. 先把 nums 放進去 set中,排除重複的數字。
2. 跑 nums迴圈,假設 nums-1 數字有在 set 中,那 nums 就不能當開頭。
3. 如果 nums-1沒有在 set 中,那就可以當開頭,計算值為1,如果 nums+1有在 set中,計算值+1,num+1。
4. 回傳最大的 curr值

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store