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;
    }
  • 相关阅读:
    7、shell函数
    5、shell分支
    6、shell循环
    4、shell中的test命令
    3、shell中引号
    2、shell变量
    1、建立和运行shell
    awk命令简介
    18、异步IO
    Python模块:sys
  • 原文地址:https://www.cnblogs.com/mickole/p/3689413.html
Copyright © 2011-2022 走看看