128. Longest Consecutive Sequence
Hard
2363134FavoriteShare
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
Accepted
244,769
Submissions
566,263
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int res=0;
unordered_set<int> st;//哈希表实现查找非常高效,因为unordered底层是哈希表实现
for(int i=0;i<nums.size();i++) st.insert(nums[i]);
for(int val:nums){//遍历vector
if(st.find(val)==st.end()) continue;
st.erase(val);
int pre=val-1,pos=val+1;
while(st.find(pre)!=st.end()) st.erase(pre--);
while(st.find(pos)!=st.end()) st.erase(pos++);
res=max(res,pos-pre-1);
}
return res;
}
};