题解 | #连续的牛群标签序列#
连续的牛群标签序列
https://www.nowcoder.com/practice/5db36ae74c274176a0cf9274e9f9ed3e
知识点
哈希
解题思路
使用了哈希集合来存储所有标签。首先,将所有标签添加到哈希集合中。然后,遍历数组中的每个数字,以该数字为起点查找连续序列。对于每个起点数字,判断是否存在 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;
}
}
查看14道真题和解析