leetcode.哈希表.128最长连续序列

1. 具体题目

给定一个未排序的整数数组,找出最长连续序列的长度。要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]  输出: 4  解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

2. 思路分析

由于题目中不要求连续序列中的元素在原数组中是有序的,对于一个数只要查找数组中是否有与其相邻的数即可,所以考虑将元素存入HashSet中,实现 O(1)时间的查询

3. 代码

 1 public int longestConsecutive(int[] nums) {
 2         HashSet set = new HashSet(); 
 3         int longest = 0;
 4         for(int num : nums){
 5             set.add(num);
 6         }
 7         for(int num : nums){ 
 8                 if(set.remove(num)){
 9                 int count = 1;
10                 int current = num;
11                 while(set.remove(--current)) count++;
12                 current = num;
13                 while(set.remove(++current)) count++;
14                 longest = Math.max(longest, count);
15              }
16         }
17         return longest;
18 }

猜你喜欢

转载自www.cnblogs.com/XRH2019/p/11824277.html