题目描述
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.
思路:
使用set保存数组中的数字,并可以去重,然后对于数组中的每个数,都去set中拿出来,然后把与该数相邻的数也从set中一次性拿出来,同时拿出一个sum加1,最后保存sum中的最大值就结果。由于会把set中的数拿出来,不会重复进行计算,所以时间复杂度在O(n)内可以完成。
代码:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int longestConsecutive(int[] num) {
Set<Integer> set = new HashSet();
for (int n : num){
set.add(n);
}
int max = 1;
for (int n : num){
if (set.remove(n)){
int val = n;
int sum = 1;
int valSmaller = n-1;
int valBigger = n+1;
while (set.remove(valSmaller)){
sum++;
valSmaller--;
}
while (set.remove(valBigger)){
sum++;
valBigger++;
}
max = Math.max(sum, max);
}
}
return max;
}
}
网友评论