标签:
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.
保证O(n)时间,通常要用map,这里每次到一个数,向前看+1数是否存在,向后看-1数是否存在,如存在,则继续滚动,length++。
时间和空间复杂度都是O(n)
public class Solution {
public int longestConsecutive(int[] nums) {
Map<Integer, Boolean> map = new HashMap<>();
for (int n : nums) {
map.put(n, false);
}
int maxLength = 0;
for (int n : nums) {
if (map.get(n)) {
continue;
}
int i = n + 1;
int length = 1;
while(map.containsKey(i)) {
map.put(i, true);
length++;
i++;
}
i = n - 1;
while(map.containsKey(i)) {
map.put(i, true);
length++;
i--;
}
if (length > maxLength) {
maxLength = length;
}
}
return maxLength;
}
}
128. Longest Consecutive Sequence
标签:
原文地址:http://www.cnblogs.com/shini/p/4467864.html