• code第一部分数组:6 数组中最长连续序列


    code第一部分数组:6  数组中最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
    For example, Given [100, 4, 200, 1, 3, 2], �e longest consecutive elements sequence is [1,
    2, 3, 4]. Return its length: 4.
    Your algorithm should run in O(n) complexity

    老样子,先分析,还是先不考虑约束条件,解决题目了再说;

    解决方案1
    先排序,直接调用STL中sort函数排序,再遍历查找最长的连续子序列;时间复杂度为O(n²)
    解决方案2
    使用hash表;用一个哈希表 unordered_map<int, bool> used 记录每个元素是否使用,对每个元素,以该
    元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。时间复杂度为O(1)

    #include <iostream>
    #include <map>
    #include <algorithm>
    using namespace std;
    
    int longestConsecutive1(int a[],int n)
    {
        sort(a,a+n);
        int longest=0;
        int i;
        for (i = 0; i < n; i++)
        {
            int length=1;
            int j;
            for (j = i+1; j<n; j++)
            {
                if (a[j]==a[j-1]+1)
                {
                    length++;
                }
                else
                    break;
            }
            int k;
            for (k = i-1; k>=0; k--)
            {
                if (a[k]==a[k+1]-1)
                {
                    length++;
                }
                else
                    break;
            }
            longest=max(longest,length);
        }
        return longest;
    }
    
    
    int longestConsecutive(int a[],int n)
    {
        map<int,int> mp;
        int i;
        for(i=0;i<n;i++)
            mp[a[i]]=1;
        int res=0;
        for(i=0;i<n;i++)
        {
            int sum=1;
            if(mp.count(a[i]))
            {
                mp[a[i]]=0;
                int left=a[i]-1;
                while(mp.count(left)&&mp[left]!=0)
                {
                    mp[left--]=0;
                    sum++;
                }
                int right=a[i]+1;
                while(mp.count(right)&&mp[right]!=0)
                {
                    mp[right++]=0;
                    sum++;
                }
            }
            if(res<sum)
                res=sum;
        }
        return res;
    }
    
    
    int main()
    {
        int a[7]={100,4,200,3,1,2,5};
    
        int ans1=longestConsecutive1(a,7);
        cout<<"ans1 is "<<ans1<<endl;
    
        int ans2=longestConsecutive(a,7);
        cout<<"ans2 is "<<ans2<<endl;
    }

    测试通过!

  • 相关阅读:
    Analysis Services 查询性能十大最佳实践(转)
    谈谈一年来对“数据仓库”概念的困惑、探索和感悟(转)
    用sql语句添加删除主键
    大文件流操作及编码
    SQL Server CONVERT() 函数
    正则表达式提取案例1
    解析SQL SERVER存储过程返回值
    文件操作类Path
    HTTP状态码
    自己写的遮罩层效果
  • 原文地址:https://www.cnblogs.com/tao-alex/p/6443011.html
Copyright © 2020-2023  润新知