128. Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Constraints:
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Example
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
思路
这道题很巧妙,一开始没有思路,标记一下。
想要在一堆数里面找出最长的连续子串,并不需要遍历每一个值来做判断,可以利用一些小技巧来排除不可能选项
- 利用HashSet,首先排除重复数字,重复数字对连续子串没有意义,可以过滤
- 因为是连续子串,也就是说前一个数和后一个数之间永远差1,那如果一个数的-1的值存在于这个集合中,那也就意味着当前值绝对不可能是最长子串的起始位了,可以过滤
题解
- 无脑快速AC
public int longestConsecutive(int[] nums) {
// 一开始用List,没有排除重复值,直接超时
HashSet<Integer> data = new HashSet<>();
Arrays.stream(nums).forEach(data::add);
int length, result;
result = 0;
for (Integer val : data) {
// 看当前值是否有前一位,如果有,那直接continue
if (data.contains(val - 1))
continue;
length = 0;
while (true) {
// 到了这边的值,代表他一定是一个子串的起始位了,那就开始往后找,每找到1个长度就+1,找不到就代表这个已经到了这个子串的结束位了
if (!data.contains(val + (++length)))
break;
}
result = Math.max(length, result);
}
return result;
}
- 优化
public int longestConsecutive(int[] nums) {
HashSet<Integer> data = new HashSet<>();
Arrays.stream(nums).forEach(data::add);
int length, result = 0;
for (Integer val : data) {
if (data.contains(val - 1))
continue;
length = 0;
// while true 有点丑陋小改一下
while (data.contains(val + length))
length += 1;
result = Math.max(length, result);
}
return result;
}
标签:Medium,val,nums,int,length,result,128,Consecutive,data
From: https://www.cnblogs.com/tanhaoo/p/17039781.html