Question
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.
code
/**
* Set集合的办法
* @param num
* @return
*/
public int longestConsecutive(int[] num) {
if (num == null || num.length == 0) {
return 0;
}
int max = 0;
Set<Integer> sets = new HashSet<>();
for (int i = 0; i < num.length; i++) {
sets.add(num[i]);
}
for (int i = 0; i < num.length; i++) {
int tempMax = 0;
int t = num[i];
while (sets.contains(t)) {
sets.remove(t);
t--;
tempMax++;
}
t = num[i] + 1;
while (sets.contains(t)) {
sets.remove(t);
t++;
tempMax++;
}
max = Math.max(max, tempMax);
}
return max;
}
本文介绍了一种寻找未排序整数数组中最长连续元素序列的算法,并提供了一个运行复杂度为O(n)的Java实现示例。该算法使用了Set集合来高效地查找连续序列。
905

被折叠的 条评论
为什么被折叠?



