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.
采用两个HashMap,一个存放在序列最小值,及其对应的长度。另一个存放序列最大值,及其对应的长度,要注意的时候,对这两个map中值的更新操作。
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
Map<Integer, Integer> big = new HashMap<Integer, Integer>();
Map<Integer, Integer> small = new HashMap<Integer, Integer>();
int max = 1;
for (int i=0; i<num.length; i++) {
int value = num[i];
if (big.get(value)!=null || small.get(value)!=null)
continue;
if (big.get(value-1)!=null && small.get(value+1)!=null) {
big.put(value, 1);
int l1 = big.get(value-1);
int l2 = small.get(value+1);
int length = l1+l2+1;
big.put(value+l2, length);
small.put(value-l1, length);
max = Math.max(max, length);
} else if (big.get(value-1) != null) {
int length = big.get(value-1)+1;
big.put(value, length);
small.put(value-length+1, length);
max = Math.max(max, length);
} else if (small.get(value+1) != null) {
int length = small.get(value+1)+1;
small.put(value, length);
big.put(value+length-1, length);
max = Math.max(max, length);
} else {
big.put(value, 1);
small.put(value, 1);
}
}
return max;
}
}