zoukankan      html  css  js  c++  java
  • LeetCode128:Longest Consecutive Sequence

    题目:

    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 should run in O(n) complexity.

    解题思路:

    考虑到题目要求的时间复杂度O(n),很自然的想到哈希表,只有哈希表的查找时间为O(1)。

    实现代码:

    #include <iostream>
    #include <vector>
    #include <unordered_set>
    using namespace std;
    
    
    /*
    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 should run in O(n) complexity.
    */
    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            if(num.empty())
                return 0;
            unordered_set<int> iset;
            vector<int>::iterator iter;
            for(iter = num.begin(); iter != num.end(); ++iter)
                iset.insert(*iter);
            
            int max = 0;
            for(iter = num.begin(); iter != num.end(); ++iter)
            {
                if(iset.count(*iter) == 1)
                {
                    int c = 1;
                    int g = *iter + 1;
                    while(iset.count(g) == 1)
                    {
                        iset.erase(g);//找到后记得要删除,不然会重复做,超时 
                        c++;
                        g++;
                    }
                    int l = *iter - 1;
                    while(iset.count(l) == 1)
                    {
                        iset.erase(l);
                        c++;
                        l--;
                    }
                    if(max < c)
                        max = c;
                    
                }
                
            }
            return max;    
        }
    };
    int main(void)
    {
        int arr[] = {100, 4, 200, 1, 3, 2};
        int n = sizeof(arr) / sizeof(arr[0]);
        vector<int> num(arr, arr+n);
        Solution solution;
        int max = solution.longestConsecutive(num);
        cout<<max<<endl;
        return 0;
    }
  • 相关阅读:
    HDU1205 吃糖果【水题】
    HDU2568 前进【水题】
    架构图初体验
    五层架构
    文件系统权限设计涉及范畴
    微服务
    领域驱动设计
    容器技术Docker
    架构总结
    仓储模式的简单理解
  • 原文地址:https://www.cnblogs.com/mickole/p/3689413.html
Copyright © 2011-2022 走看看