[leetcode]Longest Consecutive Sequence

最近经常闲的无聊,于是就做做leetcode的题了,目测好像都不是很难.

不过呢,闲的无聊还是记录下某些做了的题.

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(n*logn)的算法.

只是找连续的嘛,我们可以把所有的数字都存入hash表,然后随意从某个数字开始找他的前面和后面那个是否存在.

然后得到一个最大的长度.当然找过的就可以删掉了...你想,一个连续的序列,你从中间任意位置开始往两边找不都一样么.

所以只要找过就可以删掉了.

class Solution {
public:
    set<int> flag;
    int findBound(int n , bool asc){
        int ans = 0;
        set<int>::iterator iter;
        while((iter = flag.find(n)) != flag.end()){
            flag.erase(iter);
            ans ++;
            if(asc) n-- ; else n++;
        }
        return ans;
    }
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
            
        int ans = 0;
        flag.clear();
        for(int i = 0 ; i < num.size() ; i++)
           flag.insert(num[i]);
        for(int i = 0 ; i < num.size(); i++){
            ans = max(findBound(num[i],true) + findBound(num[i]+1,false) , ans); 
        }
        return ans;
    }
};

  ----update----

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        s.clear();
        for (int i = 0; i < num.size(); i++) {
            s.insert(num[i]);
        }
        int ans = 0;
        for (int i = 0; i < num.size(); i++) {
            ans = max(ans, bound(num[i], true) + bound(num[i] + 1, false));
        }
        return ans;
    }
private:
    unordered_set<int> s;
    int bound(int num, bool asc) {
        int cnt = 0;
        for (auto iter = s.find(num); iter != s.end(); iter = s.find(num)) {
            s.erase(iter);
            if (asc) num--; else num++;
            cnt++;
        }
        return cnt;
    }
};

  

原文地址:https://www.cnblogs.com/x1957/p/3274274.html