Longest consecutive Sequence

Source: Internet
Author: User

    /** 128.     Longest consecutive Sequence * 12.31 by Mingyang * This problem uses the uniqueness of the hashset solution, can make the time complexity of O (n). * First put all num values into HashSet, and then traverse the entire array, if there is this value in HashSet, the first to find the boundary, * Find the value of the same time the found values from the set to delete, and then look up the boundary, the same should be found in the values are deleted from the set.     So each element is traversed at most, with a time complexity of O (n). */      Public intLongestconsecutive (int[] num) {              if(num = =NULL|| Num.length = = 0)                return0; HashSet<Integer> HS =NewHashset<integer>();  for(inti = 0;i<num.length; i++) Hs.add (Num[i]); intMax = 0;  for(inti=0; i<num.length; i++){                  if(Hs.contains (Num[i])) {intCount = 1;                                    Hs.remove (Num[i]); intLow = Num[i]-1;  while(Hs.contains (Low)) {hs.remove (low); Low--; Count++; }                                        intHigh = Num[i] + 1;  while(Hs.contains (High)) {hs.remove (high); High++; Count++; } Max=Math.max (max, count); }              }              returnMax; }

Longest consecutive Sequence

Contact Us

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.