package cn.tulingxueyuan.hashTable;
import java.util.HashSet;
import java.util.Set;
public class longestConsecutiveSequence_128 {
public static void main(String[] args) {
int[] nums = new int[]{100, 4, 200, 1, 3, 2};
System.out.println(new longestConsecutiveSequence_128().longestConsecutive(nums));
}
public int longestConsecutive(int[] nums) {
Set<Integer> nums_set = new HashSet<>();
for (int num : nums) {
nums_set.add(num);
}
int longestStreak = 0;
for (int num : nums_set) {
if (!nums_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (nums_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest_streak = 0
nums_set = set(nums)
for num in nums_set:
if num - 1 not in nums_set:
current_num = num
current_streak = 1
while current_num + 1 in nums_set:
current_num += 1
current_streak += 1
longest_streak = max(longest_streak,current_streak)
return longest_streak
if __name__ == "__main__":
solution = Solution()
list = [100, 4, 200, 1, 3, 2]
print(solution.longestConsecutive(list))