Problem
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Clarification
Your algorithm should run in O(n) complexity.
Example
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Note
先排序,然后用count[]
数组记录每一位上连续序列的长度,每次循环更新最大值存为max
。
Solution
public class Solution {
public int longestConsecutive(int[] num) {
Arrays.sort(num);
int[] count = new int[num.length];
count[0] = 1;
int max = 1;
for (int i = 1; i < num.length; i++) {
if (num[i] == num[i-1]) count[i] = count[i-1];
else if (num[i] == num[i-1]+1) count[i] = count[i-1]+1;
else count[i] = 1;
max = Math.max(max, count[i]);
}
return max;
}
}