题目
思路:https://leetcode.cn/problems/longest-consecutive-sequence/solutions/2362995/javapython3cha-xi-biao-ding-wei-mei-ge-l-xk4c/?envType=study-plan-v2&envId=top-100-liked
Python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
hash_set = set(nums)
max_len = 0
for item in hash_set:
if item - 1 not in hash_set: # 必须用set, 否则会超时
tmp_val = item
while tmp_val + 1 in hash_set:
tmp_val += 1
max_len = max(max_len, tmp_val - item + 1)
return max_len
Java
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int len = 0, maxLen = 0, tmp;
for (int num : set) {
tmp = num;
if (!set.contains(num - 1)) { // 序列起点
len = 1;
while (set.contains(++tmp)) {
++len;
}
maxLen = maxLen > len ? maxLen : len;
}
}
return maxLen;
}
}