leetcode#128 longest consecutive Sequence

Source: Internet
Author: User

Original title Address

1. Plug all the elements into the collection
2. Traverse all elements, for each element, if there is not in the collection, even if there is, if any, expand to the left and right, find the longest continuous range, and at the time of each search to find the deleted. This ensures that the same sequential sequence is traversed only once, thus guaranteeing the complexity of the time.

Time complexity O (n)

Code:

1 intLongestconsecutive (vector<int> &num) {2   Set<int>record;3   intMaxLength =0;4 5    for(auto N:num)6 Record.insert (n);7 8    while(!Record.empty ()) {9     intLen =1;Ten     intn = *(Record.begin ()); One record.erase (n); A      for(inti = n-1; Record.find (i)! = Record.end (); i--) { -len++; - record.erase (i); the     } -      for(inti = n +1; Record.find (i)! = Record.end (); i++) { -len++; - record.erase (i); +     } -MaxLength =Max (maxLength, Len); +   } A  at   returnMaxLength;

leetcode#128 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.