Longest Consecutive Sequence
hard 原题链接:https://leetcode.com/problems/longest-consecutive-sequence/
Longest Consecutive Sequence
原题链接:https://leetcode.com/problems/longest-consecutive-sequence/
描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
例子
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
解法一
暴力破解
class Solution {
private:
bool arrayContains(const vector<int>& nums, int num){
for(auto n: nums){
if(n==num)return true;
}
return false;
}
public:
int longestConsecutive(vector<int>& nums) {
int longestLen=0;
for(int n : nums){
int currNum=n;
int currLen=1;
while(arrayContains(nums, currNum+1)){
currNum++;
currLen++;
}
longestLen=max(longestLen, currLen);
}
return longestLen;
}
};分析:
结果:超时
解法二
排序
解法三
哈希
使用unordered_set
使用unordered_map
总结
最后更新于
这有帮助吗?