# Leetcode-longest consecutive Sequence

Source: Internet
Author: User

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.

Solution:

`1  Public classSolution {2      Public intLongestconsecutive (int[] num) {3 4Set<integer> set =NewHashset<integer>();5         for(inti=0;i<num.length;i++) Set.add (Num[i]); 6        intMaxLen = 0;7        intindex = 0;8         while(index<num.length) {9            if(!Set.contains (Num[index])) {Tenindex++; One                Continue; A            } -  -            intLen =0; the            intval =Num[index]; -             while(Set.contains (val)) { - Set.remove (val); -len++; +val--; -            } +val = num[index]+1; A             while(Set.contains (val)) { at Set.remove (val); -len++; -val++; -            } -            if(Maxlen<len) maxlen=Len; -index++; in        } -         to  +        returnMaxLen; -          the     } *  \$}`

Leetcode-longest consecutive Sequence

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.