标签:序列 stc spl public leetcode pre display div 操作
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/
代码:
class Solution { public: int longestConsecutive(vector<int>& nums) { int n = nums.size(); if(n == 0) return 0; if(n == 1) return 1; set<int> s; for(int i = 0; i < n; i++) { s.insert(nums[i]); } int res = 1; for(int i = 0; i < n; i++) { if(s.find(nums[i]-1) == s.end()) { int cur_num = nums[i]+1; int cur_res = 1; while(s.find(cur_num) != s.end()) { cur_num++; cur_res++; res = max(res, cur_res); } } } return res; } };
思路:构造哈希表来实现查询,哈希是 O(1)的,故可以通过将每个值加入哈希表,找到最小的那个值在测试++ 是否在 hashtable中来完成 O(n)操作。
标签:序列 stc spl public leetcode pre display div 操作
原文地址:https://www.cnblogs.com/FriskyPuppy/p/12940496.html