128.最长连续序列
# 128.最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
输入:nums = [100,4,200,1,3,2] 输出:4 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
- 先Arrays.sort(nums)排序后再找,时间O(nlogn)或者O(n^2)。
- 空间换时间,用HashSet记录nums数组。然后遍历HashSet用中心扩散法,把一个元素左边相连区间和右边相连区间的元素从HashSet中删去,并记录比较该区间长度。这里有一个坑,遍历HashSet过程中外层循环不能够写成for(Integer i:HashSet),因为里层要HashSet.remove()删去整个区间内元素,容器会报异常,遍历过程中不能够对容器添加删除。因此外层要用nums遍历。
for(int i:nums)
{
if(hashset.remove(i))
{
int curr=i,left =curr - 1, right = curr + 1;
while (hashset.remove(right)) right++;
while (hashset.remove(left)) left--;
res=right-left-1>res?right-left-1:res;
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
当容器中元素是Integer类型时,remove()方法可以是int类型,遍历容器时for(Integer i:hashset)。
hashset.remove(e)可以同时用来判断是否存在,不存在则返回false,存在且删除成功返回true。
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57