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.
題意:給出一個(gè)無(wú)序數(shù)組,求這個(gè)無(wú)序數(shù)組中最大的連續(xù)數(shù)組長(zhǎng)度,要求時(shí)間復(fù)雜度是O(n)。
思路:自己沒(méi)有想到解題思路,參考的是http://www.cnblogs.com/grandyang/p/4276225.html給出的解法。用set標(biāo)記全部元素,然后遍歷數(shù)組,找每個(gè)元素的最左和最右,找的部分都從set中移除,然后求左右邊界差值,更新最大長(zhǎng)度。
public int longestConsecutive(int[] nums) {
int res = 0;
if (nums == null || nums.length == 0) {
return res;
}
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
for (int num : nums) {
if (set.remove(num)) {
int left = num - 1;
while (set.remove(left)) {
left--;
}
int right = num + 1;
while (set.remove(right)) {
right++;
}
res = Math.max(res, right - left - 1);
}
}
return res;
}