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.
class Solution {
public int longestConsecutive(int[] nums) {
int res =0;
if(nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
Map<Integer,Integer> value = new HashMap<>();
for(int index=0;index<nums.length;index++) {
int i = nums[index];
if(index!=0 && i==nums[index-1]) {
continue;
}
value.put(i, value.getOrDefault(i, 0)+1);
res = Math.max(res, value.get(i));
value.put(i+1, value.getOrDefault(i+1, 0)+value.get(i));
}
return res;
}
}