力扣128. 最长连续序列

 

自己没想到最优解,题解的思路记录一下吧

题目:【https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-interview-150

 

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int>& nums) {
 4         unordered_set<int> cache;
 5         int ret = 0;
 6 
 7         for (auto n : nums)
 8             cache.insert(n);
 9 
10         for (auto n : cache) {
11             if (0 == cache.count(n - 1)) {
12                 int tret = 1;
13                 while (cache.count(++n)) tret++;
14                 ret = tret > ret ? tret : ret;
15             }
16         }
17         return ret;
18     }
19 };

 

posted @ 2025-04-27 10:33  J&YANG  阅读(7)  评论(0)    收藏  举报