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.
Public classSolution { Public intLongestconsecutive (int[] nums) {Map<Integer,Integer> map =NewHashmap<integer,integer>(); intLongest = 0; intSize =nums.length; for(inti=0;i<size;i++) { if(Map.containskey (Nums[i]))Continue;//Exclude DuplicatesMap.put (nums[i],1); intStart =Nums[i]; intEnd =Nums[i]; if(Map.containskey (nums[i]+1)) end = Nums[i]+map.get (nums[i]+1); if(Map.containskey (nums[i]-1)) start = Nums[i]-map.get (nums[i]-1); Longest= Math.max (longest,end-start+1); Map.put (Start,end-START+1);//Update left boundaryMap.put (end,end-start+1);//Update right boundary } returnlongest; }}
Longest consecutive Sequence *