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.
classSolution{publicintlongestConsecutive(int[] nums){int n = nums.length;if(n<=1){return n;}
HashSet<Integer> set =newHashSet<>();for(int a : nums){
set.add(a);}int max =1;//虽然是两层循环, 但是每个元素最多访问两次, 所以时间复杂度是O(N)for(int i=0; i<n; i++){int cur = nums[i];//如果不存在nums[i]-1, 说明nums[i]是一个序列的最小值, 接下来看看这个序列的长度if(!set.contains(cur-1)){int len =1;while(set.contains(cur+1)){
len++;
cur++;}
max = Math.max(max, len);}}return max;}}
welcome to my blogLeetCode Top 100 Liked Questions 128. Longest Consecutive Sequence (Java版; Hard)题目描述Given an unsorted array of integers, find the length of the longest consecutive elements sequen...