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.
» Solve this problem
用了HashMap,不能严格地说是O(n)。
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> expand = new HashMap<Integer, Integer>();
for (int i = 0; i < num.length; i++) {
expand.put(num[i], 1);
}
int max = 0;
for (int i = 0; i < num.length; i++) {
if (expand.get(num[i]) != -1) {
int q = 1;
Integer k = num[i] + 1;
Integer v = expand.get(num[i] + 1);
while (v != null) {
expand.put(k, -1);
q += v;
k += v;
v = expand.get(k);
}
expand.put(num[i], q);
if (q > max) {
max = q;
}
}
}
return max;
}
}