求出最长连续序列,并打印出序列

来源:互联网 发布:商丘学院网络教学平台 编辑:程序博客网 时间:2024/06/02 23:56
#include <iostream>#include <unordered_map>using namespace std;int longestConSeq(int* a, int n, int& small, int& big){    unordered_map<int, bool> m;    for (int i = 0; i < n; i++)    {        m[a[i]] = false;    }    int max = 0;    int low = 0, high = 0, pos = 0;    for (int i = 0; i < n; i++)    {        if (m[a[i]])        {            continue;        }        int len = 1;        m[a[i]] = true;        for (int j = a[i]+1; m.find(j) != m.end(); j++)        {            m[j] = true;            len++;            high++;        }        for (int j = a[i]-1; m.find(j) != m.end(); j--)        {            m[j] = true;            len++;            low++;        }        if (len > max)        {            max = len;            pos = i;        }    }    small = a[pos] - low;    big = a[pos] + high;    return max;}int main(){    int a[] = {100, 3, 200, 4, 1, 2, 5};    int small, big;    cout << longestConSeq(a, sizeof(a)/sizeof(a[0]),small, big) << endl;    for (int i = small; i <= big; i++)    {        cout << i << " ";    }    cout << endl;    return 0;}


0 0
原创粉丝点击