Description
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution
给一个未排序数组,找到最长的连续子集的长度。要求常数时间。
Using a map to store number and its subsequence’s length. For nums not in map, get its left neighbor and right neighbor’s subsequence length. Update it to res and map and its edge, because they are in the same subsequence. We must keep head and tail element have right updated length value.
If this num is in map, just continue. Of course, it is optional.
Code
class Solution {
public int longestConsecutive(int[] nums) {
int res = 0;
//a map from num to its subsequence's length.
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums){
if (!map.containsKey(i)){
//get neighbors subsequence's length if exist.
int left = map.containsKey(i - 1) ? map.get(i - 1) : 0;
int right = map.containsKey(i + 1) ? map.get(i + 1) : 0;
//calcualte new list length, if no neighobrs, 1;
int sum = left + right + 1;
res = Math.max(res, sum);
//put new list length into map, update other edge's length value
map.put(i, sum);
map.put(i - left, sum);
map.put(i + right, sum);
}
else{
//duplicate circumstance;
continue;
}
}
return res;
}
}
Time Complexity: O(n)
Space Complexity: O(n)