Solution 1Set Expand
Python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
numSet = set(nums)
maxSeqLen = 0
while maxSeqLen < len(numSet):
num = numSet.pop()
longest = num+1
while longest in numSet:
numSet.remove(longest)
longest += 1
num = num-1
while num in numSet:
numSet.remove(num)
num -= 1
maxSeqLen = max(maxSeqLen, longest-num-1)
return maxSeqLenSolution 2Sort Scan
Java
public int longestConsecutive(int[] nums) {
if (nums.length == 0) { return 0; }
Arrays.sort(nums);
int max = 1;
int count = 1;
for (int i=1; i<nums.length; i++) {
if (nums[i] == nums[i-1] + 1) {
count++;
} else if (nums[i] == nums[i-1]) {
continue;
} else {
max = Math.max(count, max);
count = 1;
}
}
return Math.max(count,max);
}Solution 3Sequence Start
Java
public int longestConsecutive2(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int maxCount = 0;
for (int num: nums) {
if (!set.contains(num-1)) {
int count = 1;
while (set.contains(++num)) {
count++;
}
maxCount = Math.max(count, maxCount);
}
}
return maxCount;
}