Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
**Input:** nums = [100,4,200,1,3,2]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
publicintlongestConsecutive(int[] num) {int res =0;HashMap<Integer,Integer> map =newHashMap<Integer,Integer>();for (int n : num) {if (!map.containsKey(n)) {int left = (map.containsKey(n -1)) ?map.get(n -1) :0;int right = (map.containsKey(n +1)) ?map.get(n +1) :0;// sum: length of the sequence n is inint sum = left + right +1;map.put(n, sum);// keep track of the max length res =Math.max(res, sum);// extend the length to the boundary(s)// of the sequence// will do nothing if n has no neighborsmap.put(n - left, sum);map.put(n + right, sum); }else {// duplicatescontinue; } }return res;}