
Python:
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums_set =set(nums)
max_cnt =0
for x in nums_set:
current_num = x
current_cnt = 1
if x-1 not in nums_set:
while current_num + 1 in nums_set:
current_num+=1
current_cnt+=1
max_cnt =max(current_cnt,max_cnt)
return max_cnt
注意:
-
集合的特性:集合(
set)是一个无序的、不重复的元素集合。在 Python 中,set的查找操作(如in)的时间复杂度是 O(1),即平均情况下是常数时间复杂度。这是因为集合底层是通过哈希表实现的。 -
时间复杂度对比:
-
使用集合:时间复杂度为 O(n),因为集合的查找操作是 O(1)。
-
不使用集合:时间复杂度为 O(n²),因为列表的查找操作是 O(n)。
-
C++:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int>nums_set(nums.begin(),nums.end());
long long int max_cnt = 0;
for(int x : nums_set){
long long cnt = 1;
int current_num = x;
if(!nums_set.count(current_num-1)){
while (nums_set.count(current_num+1)){
current_num++;
cnt++;
}
}
max_cnt=max(cnt,max_cnt);
}
return max_cnt;
}
};
8万+

被折叠的 条评论
为什么被折叠?



