# Leetcode [No. 128] Longest Consecutive Sequence (MEDIUM) 解題心得 ## 題目 https://leetcode.com/problems/longest-consecutive-sequence/description/ ## 思路 + 這個解法是參考Neetcode YT寫出來的,找到最左邊的數字後去consecutiive尋找 + 比較特別的是第四行跟第七行,算是增快速度所改的 ```c++= class Solution { public: int longestConsecutive(vector<int>& nums) { if(nums.size()<2) return nums.size(); unordered_set<int> s(nums.begin(), nums.end()); int res = 0; for (auto num:s) // replace nums as s can success remove redundant integer in set { if(s.count(num-1) == 0) { int curNum = num; int curIter = 0; while(s.count(curNum)) { curIter++; curNum++; } res = max(res, curIter); } } return res; } }; ``` ### 解法分析 + time complexity: O(N) ### 執行結果 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up