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.
Ideas:
Use set to store the different elements in the array first. The elements within the set are then searched sequentially, as follows:
1. Read the header element A in the collection and remove it from the collection;
2. Find the value of A+1 in the collection (Set.contains () method), if any, delete the element, continue to find a+2...a+m,a+m+1 does not exist, then jump out of the loop;
3. Find the value of A-1 in the collection exists, if there is an element, continue to find a-2...a-p,a-p-1 does not exist, then jump out of the loop;
4. The value of the record m+p+1 is the longest sequential number found, comparing it with Max and selecting the maximum;
5. Select the head element again, repeating the process until the collection element is traversed.
Code: (Java)
1 Public classSolution {2 Public intLongestconsecutive (int[] nums) {3 if(nums.length==1){4 return1;5 }6Set<integer> Arrset =NewHashset<integer>();7 for(inti=0;i<nums.length;i++){8 Arrset.add (Nums[i]);9 }TenIterator<integer> iter =arrset.iterator (); One intMax = 0; A while(Iter.hasnext ()) { - intCount1=0; - intCount2=0; the intA = Iter.next () +1; - intb = a-2; - Iter.remove (); -Iterator<integer> it1 =arrset.iterator (); + if(It1.hasnext ()) { - while(It1.hasnext () && arrset.contains (a++)){ +count1++; AArrset.remove (A-1); at } - } -Iterator<integer> it2 =arrset.iterator (); - if(It2.hasnext ()) { - while(It2.hasnext () && arrset.contains (b--)){ -count2++; inArrset.remove (b+1); - } to } +max = Math.max (max,count1+count2+1); -ITER =arrset.iterator (); the } * returnMax; $ }Panax Notoginseng}
[Leetcode] Longest consecutive Sequence