Description
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.
分析
题目的意思是:给你一个数组,找求最长连续串的长度。
- 首先建立一个hash表,然后初始化存储所有的数据元素。遍历数组,然后去找相关的hash表的值,如果找到了,就删除,并且重复遍历其相邻的hash表的值。就行了
C++
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hashSet(nums.begin(),nums.end());
int res=0;
for(int val:nums){
if(!hashSet.count(val)){
continue;
}
hashSet.erase(val);
int pre=val-1;
int next=val+1;
while(hashSet.count(pre)){
hashSet.erase(pre);
pre--;
}
while(hashSet.count(next)){
hashSet.erase(next);
next++;
}
res=max(res,next-pre-1);
}
return res;
}
};
Python
通过hashset来判断数值是否连续,能够实现O(1)的时间复杂度,否则的话就要从头到尾的找,这样就是O(n)的复杂度了。另外为了减少重复的查找操作,我们从最小数开始,即在遍历的时候加了一个判断,参考代码。
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums)==0:
return 0
max_len = 1
num_set = set(nums)
for num in nums:
if num -1 not in num_set:
cur_num = num
cur_count = 1
while cur_num+1 in num_set:
cur_num+=1
cur_count+=1
max_len = max(max_len, cur_count)
return max_len