描述
在一个农场里,有n头牛,每头牛都有一个唯一的标签编号。农场主人想找出所有牛的标签中,存在的最长连续标签序列的长度。
你需要返回一个整数,表示连续标签的最长序列的长度。
注意:请不要使用排序,且在 O(n) 时间复杂度内完成此题。
示例1
输入:[10,4,20,1,3,2]
返回值:4
说明:连续序列最长为[1,2,3,4]
示例2
输入:[0,3,7,2,5,8,4,6,0,1]
返回值:9
备注:
0 <= n <= 10^5
0 <= tag[i] <= 10^8
知识点
哈希
解题思路
使用了哈希集合来存储所有标签。首先,将所有标签添加到哈希集合中。然后,遍历数组中的每个数字,以该数字为起点查找连续序列。对于每个起点数字,判断是否存在 num-1,如果存在,则表示 num 不是连续序列的起点,跳过继续下一个数字。否则,我们以 num 为起点,不断向后查找 num+1,同时更新当前序列的长度。最后,通过比较当前序列长度和最长序列的长度来更新最长序列的长度。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tag int整型一维数组
* @return int整型
*/
public int longestConsecutive (int[] tag) {
// write code here
HashSet<Integer> set = new HashSet<>();
for (int num : tag) {
set.add(num);
}
int longestLength = 0;
for (int num : tag) {
if (set.contains(num - 1)) {
continue;
}
int currentNum = num;
int currentLength = 1;
while (set.contains(currentNum + 1)) {
currentNum++;
currentLength++;
}
longestLength = Math.max(longestLength, currentLength);
}
return longestLength;
}
}