给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
1.建立hash表,把数值存入
2.判断当前数值有没有前驱,没有的话就以当前节点去hash表中查找后驱
3.长度为y-x+1
class Solution {
public int longestConsecutive(int[] nums) {
//建立hash表,把数值存入
//判断当前数值有没有前驱,没有的话就以当前节点去hash表中查找后驱
//长度为y-x+1
Set<Integer> hash = new HashSet<>();
for(int x: nums) hash.add(x);
int max = 0;
for(int x : nums){
if(!hash.contains(x-1)){
int y = x;
while(hash.contains(y+1)) y++;
max= Math.max(max , y-x + 1);
}
}
return max;
}
}