Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
思路:
a. 如果不考虑时间复杂度O(n)的要求,则可以先排序,排序的时间复杂度平均情况下为O(nlogn)。然后遍历排序后的数组,统计连续字符的个数。由于本题有O(n)的限制,故不用此方法。
b. 首先遍历一遍数组,找到最大的数200。然后申请一个 0 ~ 199大小的数组空间。遍历数组[100, 4, 200, 1,3, 2],并修改新数组对应位置的值为1,如图。随后,统计新数组中连续1的个数,也是一个O(n)的时间复杂度。缺点是需要申请很大的空间,空间开销大。
c. 看了Discuss里的方法,有人用HashSet存储数组中的数,HashSet的查找在不考虑冲突等情况下,默认为O(1)。随后,统计连续出现的数字个数,假设从2开始统计,则循环看3、4、5…是否也在HashSet中。需要注意的是,如果1存在于HashSet中,则不用统计2了,因为在统计1的时候会重复统计2。不太好用文字解释,看一下代码立刻就理解了。
代码:
public class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int n : nums) {
set.add(n);
}
int longest = 0;
for(int n : set) {
if(!set.contains(n-1)) {
int m = n + 1;
while(set.contains(m)) {
m++;
}
longest = Math.max(longest, m - n);
}
}
return longest;
}
}