Longest consecutive elements 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 shold run in O (N) Complexity.

 

Use the map template,

Map records the maximum continuous intervals. Use two keywords to search, from small to large, and from large to small

The main idea is that the newly added elements merge between two intervals, namely [..., A-1] a [A + 1.

Why can we get the optimal solution: greedy algorithm

Because every new element is merged as much as possible, and the maximum continuous interval containing the element is obtained.

 

 

using namespace std;class Solution {public:    int longestConsecutive(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        unordered_map<int, bool> set;        unordered_map<int, int> range;        int max = 0;        for(int i = 0; i < num.size(); i++)        {            if(!set[num[i]])            {                set[num[i]] = 1;                int left = num[i];                int right = num[i];                if(range.count(num[i] - 1) &&                     range[num[i] - 1] <= num[i] - 1)                    {                        left = range[num[i] - 1];                        range.erase(num[i] - 1);                    }                 if(range.count(num[i] + 1) &&                     range[num[i] + 1] >= num[i] + 1)                    {                        right = range[num[i] + 1];                        range.erase(num[i] + 1);                    }                 range[left] = right;                 range[right] = left;                 if(max < right - left + 1)                    max = right - left + 1;            }        }        return max;    }};

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.