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[i]+1==A[i+1],那么就是连续的,这时记录下当前连续的长度,更新最大值即可。
AC代码:
public int longestConsecutive(int[] nums) {
int len = nums.length;
if(len == 0 || len == 1){
return len;
}
Set<Integer> set = new TreeSet<Integer>();
for(int i=0;i<len;i++){
set.add(nums[i]);
}
Iterator<Integer> it = set.iterator();
int pre = 0;
if(it.hasNext()){
pre = it.next();
}
int max = 1;
int count = 1;
while(it.hasNext()){
int cur = it.next();
if(cur == pre + 1){
count++;
}
else{
max = count > max ? count : max;
count=1;
}
pre = cur;
}
max = count > max ? count : max;
return max;
}
只用了17ms。但是这种方法是不符合题目要求的。
因为这里用的TreeSet构造的有序集合,由于TreeSet是红黑树结构,单个插入的时间复杂度是O(logn),所以整个数组插入就是O(nlogn)了。
更新:
首先想想当我们自己去找最长链的时候,第一步当然是去找到一条链,比如1,2,3,4这条链,那么我们先要找到这条链的起始1,然后依次往下面数,数到4的时候数完,那么这条链的长度就是4,其他的链也是这么数,数完所有的链也就得到最长链的长度了。
编码也可以按照这个思路进行,关键在于如何找到每条链的起始点,起始点i有什么特征呢,特征在于集合里面不包含i-1,因此得到如下算法:
public int longestConsecutive(int[] nums) {
if(nums.length == 0 || nums.length == 1){
return nums.length;
}
Set<Integer> set = new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
set.add(nums[i]);
}
int max = 1;
for(int i : set){
int cur = i;
if(!set.contains(i-1)){
int count = 0;
while(set.contains(cur)){
count++;
cur++;
}
max = count > max ? count : max;
}
}
return max;
}
外层循环遍历整个set,内层只在找个每个链的起始时,走到链的末尾,因此整个时间复杂度还是O(n)