给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
思路:我们将数组存在hashset中,这样查找可以做到O(1),同时,我们只对 当前数字 - 1 不在哈希表里的数字,作为连续序列的第一个数字去找对应的最长序列,这是因为其他数字一定已经出现在了某个序列里。
class Solution {
public int longestConsecutive(int[] nums) {
int ans=0;
Set<Integer> st=new HashSet<Integer>();
for(int num:nums)
st.add(num);
for(int num:st)
{
if(!st.contains(num-1))
{
int tmp=num;
int len=1;
while(st.contains(tmp+1))
{
len++;
tmp++;
}
ans=Math.max(ans, len);
}
}
return ans;
}
}