|  | 
 
| 问题:给定一个未排序的整数数组,请找出最长的连续元素序列的长度。 您的算法应以O(n)复杂度运行。
 示例:
 输入:  [100,4,200,1,3,2]
 输出: 4
 说明:最长的连续元素序列是[1, 2, 3, 4]。因此,它的长度是4。
 解析:将所有数放入集合中,确保所有数唯一,通过使用两个数字记录,当集合中包含当前数的下一个数时,num自增,curMax记录num的最大值
 代码:
 class Solution {
 public int longestConsecutive(int[] nums) {
 HashSet<Integer> hs = new HashSet<Integer>();
 for(int num : nums) hs.add(num);
 
 if(nums.length == 0) return 0;
 
 int max = 1;
 
 for(int num : nums){
 if(hs.contains(num - 1)) continue;
 int currMax = 1;
 while(hs.contains(num + 1)){
 num++;
 currMax++;
 }
 max = Math.max(currMax, max);
 }
 
 return max;
 }
 }
 
 | 
 |